Search code examples
gogorilla

How to send back an image in Go from the public folder?


I'm new to go if it's an obvious question then sorry but I didn't find anything so I'm posting here.

This is a two-part question actually.

1) So I have this web folder in my project dir. And it is public and I have a middleware function which is checking for the JWT.

I'm using this logic to avoid JWT auth but it's now working. I'm getting unauthorized.

// List of endpoints that don't require auth by an access token
        notAuth := []string{"/", "/refreshtokens", "/students/signup", "/students/signin", "/students/forgotpassword",
            "/images"}

        // Current request path
        requestPath := r.URL.Path

        // Check if the request does not need authentication, serve the request if it doesn't need it
        for _, value := range notAuth {

            if value == requestPath {
                next.ServeHTTP(w, r)
                return
            }
        }

So how can I put this URL inside the array so it can escape the JWT authorization?

2) This is how I'm making the folder public but I don't want this.

router.PathPrefix("/images").Handler(http.StripPrefix("/images", http.FileServer(http.Dir("./web/"))))

What I want is something like

router.Handle("/image/{imageName}",func(w http.ResponseWriter, request *http.Request){
http.ServeFile(this image name file)
})

So I can send back the file which is requested.

Any help will be appreciated.


Solution

  • For #1: clearly the request path is not one of those in notAuth. Maybe you need to check if the path has a prefix that is included in notAuth? If that is so, you need to be careful about /, as it will pass all paths. If not, log the request path and see what the problem is.

    For #2: you should be able to do:

    http.ServeFile(w,request,filepath.Join(baseDir,mux.Vars(request)["imageName"])