julienschmidt / httprouter

A high performance HTTP request router that scales well
https://pkg.go.dev/github.com/julienschmidt/httprouter
BSD 3-Clause "New" or "Revised" License
16.56k stars 1.47k forks source link

using httprouter to serve static images from many different directories on disk #241

Open rcholic opened 6 years ago

rcholic commented 6 years ago

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 pathn: /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)
acud commented 6 years ago

@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(!).