feat(filehole): serve files straight from filehole

Previously these were served by nginx
This commit is contained in:
hgc 2023-04-13 15:50:36 +00:00
parent 46c162d494
commit a04c4afbdd
2 changed files with 22 additions and 4 deletions

11
main.go
View File

@ -86,7 +86,7 @@ func UploadHandler(w http.ResponseWriter, r *http.Request) {
log.Info().Str("mtype", mtype.String()).Str("ext", mtype.Extension()).Int64("expiry", sanExpiry).Int64("url_len", sanUrlLen).Msg("Writing new file")
f, err := os.OpenFile(viper.GetString("filedir")+name, os.O_WRONLY|os.O_CREATE, 0644)
f, err := os.OpenFile(viper.GetString("filedir")+"/"+name, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Error().Err(err).Msg("Error opening a file for write")
w.Write([]byte("internal error\n"))
@ -96,7 +96,7 @@ func UploadHandler(w http.ResponseWriter, r *http.Request) {
io.Copy(f, file)
w.Write([]byte("https://" + viper.GetString("vhost") + "/" + name + "\n"))
w.Write([]byte(viper.GetString("vhost") + "/u/" + name + "\n"))
}
func ExpiryDoer() {
@ -112,7 +112,7 @@ func ExpiryDoer() {
continue
}
if time.Now().After(time.Unix(expiryTime, 0)) {
os.Remove(viper.GetString("filedir") + string(k))
os.Remove(viper.GetString("filedir") + "/" + string(k))
removed += 1
c.Delete()
}
@ -135,7 +135,7 @@ func main() {
viper.SetDefault("bind", "127.0.0.1:8000")
viper.SetDefault("database", "filehole.db")
viper.SetDefault("filedir", "./data")
viper.SetDefault("vhost", "127.0.0.1:8000")
viper.SetDefault("vhost", "http://127.0.0.1:8000")
viper.SetConfigName("config")
viper.SetConfigType("toml")
@ -187,6 +187,9 @@ func main() {
}
r := mux.NewRouter()
r.PathPrefix("/u/").Handler(http.StripPrefix("/u/", NoDirectoryList(http.FileServer(http.Dir(viper.GetString("filedir"))))))
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(indexPage)
}).Methods("GET")

15
util.go Normal file
View File

@ -0,0 +1,15 @@
package main
import (
"net/http"
)
func NoDirectoryList(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "" {
http.Error(w, "404 page not found", 404)
return
}
h.ServeHTTP(w, r)
})
}