Is there a way to pass in headers through Http.Handle or Http.FileServer?

Viewed 931

I have a very basic server set up in Go

fs := http.FileServer(http.Dir("./public"))
 http.Handle("/",fs)

Here's the problem though: I want people to access my URL's with fetch(). This isn't possible, however due to CORS being set.

Access to fetch 'xxxxx' from origin 'null' has
been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch 
the resource with CORS disabled.

I need to find a way to pass in the header Access-Control-Allow-Origin:*, but I don't know how to with http.Handle or http.FileServer, only http.HandleFunc.

I can't use http.HandleFunc because as far as I know it doesn't allow me to serve files, and I'd rather not get files myself using a file handling system (I may have to do this as a last resort unless there is another way). Plus, it's inefficient. Why reinvent the wheel, especially when that wheel is way better than what I could come up with?

Is there any way whatsoever to send headers with http.Handle()?

I am fairly new to Go, and I haven't done statically typed languages in a while, nor have I done languages that handle incoming URL's (I mainly used PHP, so...), so I may or may not have a good grasp on the concept.

1 Answers

You can wrap a http.FileServer in a http.HandleFunc:

func cors(fs http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // do your cors stuff
        // return if you do not want the FileServer handle a specific request
        
        fs.ServeHTTP(w, r)
    }
}

Then use it with:

fs := http.FileServer(http.Dir("./public"))
http.Handle("/", cors(fs))

The underlying mechanism is that http.HandlerFunc implements the http.Handler interface.

Related