cors
cors copied to clipboard
How to use with DefaultServeMux
Hi there,
My go skills are not super advanced, so I was wondering if there is a simple way to use this nice cors library with DefaultServeMux
Would it be possible to attach the CORS settings on specific functions/routes in the example below
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
Thanks
In case anyones knowledge is as basic as mine, looks like you can do this by explicitly defining the mux server
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://foo.bar"},
})
mux := http.NewServeMux()
mux.Handle("/foo", fooHandler)
mux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", c.Handler(mux)))
:+1:
@sammy yes, it's correct
instead of creating a new mux you can just pass http.DefaultServeMux to c.Handler()
@rs This issue could be closed.