serve files downloaded by ()meme command directly instead of relying on external router

This commit is contained in:
lyx0 2024-01-17 19:56:33 +01:00
parent 2802c4e07a
commit 8f685cb3e2

View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"net/http" "net/http"
"os"
"sort" "sort"
"strings" "strings"
@ -20,6 +21,10 @@ func (app *application) startRouter() {
router.GET("/commands", app.commandsRoute) router.GET("/commands", app.commandsRoute)
router.GET("/timer/:channel", app.channelTimersRoute) router.GET("/timer/:channel", app.channelTimersRoute)
// Serve files uploaded by the meme command, but don't list the directory contents.
fs := justFilesFilesystem{http.Dir("/public/uploads/")}
router.Handler("GET", "/uploads/*filepath", http.StripPrefix("/uploads", http.FileServer(fs)))
app.Log.Fatal(http.ListenAndServe(":8080", router)) app.Log.Fatal(http.ListenAndServe(":8080", router))
} }
@ -181,3 +186,28 @@ func (app *application) statusPageRoute(w http.ResponseWriter, r *http.Request,
fmt.Fprintf(w, fmt.Sprintf("started: \t%v\nenvironment: \t%v\ncommit: \t%v\ngithub: \t%v", started, app.Environment, commit, commitLink)) fmt.Fprintf(w, fmt.Sprintf("started: \t%v\nenvironment: \t%v\ncommit: \t%v\ngithub: \t%v", started, app.Environment, commit, commitLink))
} }
// Since I want to serve the files that I uploaded with the meme command to the /public/uploads
// folder, but not list the directory on the `/uploads/` route I found this issue that solves
// that problem with the httprouter.
//
// https://github.com/julienschmidt/httprouter/issues/25#issuecomment-74977940
type justFilesFilesystem struct {
fs http.FileSystem
}
func (fs justFilesFilesystem) Open(name string) (http.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return neuteredReaddirFile{f}, nil
}
type neuteredReaddirFile struct {
http.File
}
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}