Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65905008/is-there-a-way-to-pass-in-headers-through-http-handle-or-http-fileserver

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...