httprouter
httprouter copied to clipboard
using httprouter to serve static images from many different directories on disk
I am using httprouter in a project and I now need to make it work with the go http server to serve image files from a few different directories, for example:
images in path1: /root/path1/to/images_part1
images in path2: /root/path2/to/images_part2
...
images in path_n_: /root/pathn/to/images_partn
In my code, I have the following working in supporting what I wanted to do, but I was wondering if there is any negative impact on my http server using httprouter:
r := httprouter.New()
imagePaths := []string{"/root/path1/to/images_part1/cool_me.jpeg", "/root/path2/to/images_part2/128.png",
"/root/path3/to/images_part3/imagen.jpeg"}
// get the code executive path:
ex, err := os.Executable()
if err != nil {
panic(err)
}
for idx, imgPath := range imagePaths {
if rel, err := filepath.Rel(ex, imgPath); err != nil {
logrus.Errorf("err in getting relative path: %v\n", err)
} else {
logrus.Infof("for image: %s, rel dir is %s\n", imgPath, filepath.Dir(rel))
r.ServeFiles(fmt.Sprintf("/static%d/*filepath", idx), rice.MustFindBox(filepath.Dir(rel)).HTTPBox()) // here, create many different static paths to httprouter
}
}
http.ListenAndServe(":8888", r)
@rcholic this would probably work but in my experience not considered a best practice. http files are usually served from within one directory, security reasons being one of the considerations (does the process have the right permissions to access the files, etc, this is usually trivial using a local dev environment but not when containerising applications for example). you'd typically want to know exactly where all of your files are, which process accesses them, how, and not using relative paths(!).