router.PathPrefix("/test/").Handler(http.StripPrefix("/test/", http.FileServer(http.Dir("/assets/"))))
In this example, the root directory of the file server is set to /assets/
. My goal is to set this root directory based on the cookie in the HTTP request. I know I am able to do something like this:
type AlternativeFileServer struct { }
func AlternativeFileServerFactory() http.Handler {
return AlternativeFileServer{}
}
func (aFs AlternativeFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := GetCookie(r)
if err != nil {
// handle error
}
var rootDirectory string
if cookie == "x" {
rootDirectory = "assets"
} else {
rootDirectory = "alternative"
}
path := filepath.join(rootDirectory, r.URL.Path) + ".png"
http.ServeFile(path)
}
func main() {
....
router.PathPrefix("/test/").Handler(http.StripPrefix("/test/", AlternativeFileServerFactory())
}
But I was hoping there was a better alternative where I could wrap the http.FileServer directly and dynamically set its root directory.
Is that possible?