Answer the question
In order to leave comments, you need to log in
How to specify CORS for http.FileServer in GO?
Hello, please tell me how to specify header headers for http.FileServer?
i.e. I understand that I need to write this:
but I don’t understand where ...
here is the whole code:w.Header().Set("Access-Control-Allow-Origin", "*")
func initServer(pathToStatic string, c chan <- string ){
port := "46424"
http.Handle("/static/", http.StripPrefix(strings.TrimRight("/static/", "/"), http.FileServer(http.Dir(pathToStatic))))
log.Printf("Serving %s on HTTP port: %s\n", pathToStatic, port)
c <- fmt.Sprintf("http://localhost:%s/static/", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
Answer the question
In order to leave comments, you need to log in
Suggested solution:
var orig = http.StripPrefix("/static/", http.FileServer(http.Dir(".")))
var wrapped = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header.Set("Access-Control-Allow-Origin", "*")
// …
orig.ServeHTTP(w, r)
})
http.Handle("/static/", wrapped)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question