cors icon indicating copy to clipboard operation
cors copied to clipboard

How to use with DefaultServeMux

Open sammy opened this issue 5 years ago • 3 comments

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

sammy avatar Mar 17 '20 13:03 sammy

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 avatar Mar 18 '20 14:03 sammy

@sammy yes, it's correct

tarasyarema avatar Mar 19 '20 13:03 tarasyarema

instead of creating a new mux you can just pass http.DefaultServeMux to c.Handler()

beaugunderson avatar Mar 14 '21 05:03 beaugunderson

@rs This issue could be closed.

jub0bs avatar Sep 10 '23 08:09 jub0bs