M
M
Make Now2019-09-16 12:16:03
go
Make Now, 2019-09-16 12:16:03

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))
}

Thanks..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Make Now, 2019-09-16
@makenow

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)

Thanks Ainar-G

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question