0

I wrote a simple API with the Gorilla Web Toolkit, handling the CORS answers through its handlers:

r := mux.NewRouter()
r.HandleFunc("/api/note", readHandler).Methods("GET")
r.HandleFunc("/api/note", writeHandler).Methods("POST")
r.HandleFunc("/api/note", deleteHandler).Methods("DELETE")
r.HandleFunc("/api/note", optionsHandler).Methods("OPTIONS")

optionsHandler is

func optionsHandler(_ http.ResponseWriter, _ *http.Request) {
    return
}

My rationale behind this is that a Preflight call will use OPTIONS but the only thing it is interested in are the relevant CORS headers.

GET and POST work fine, a JavaScript fetch() call goes through with the right headers.

DELETE however fails on the Preflight call: Chrome DevTools states that a DELETE + Preflight call fails with CORS error, the next line is the Preflight OPTIONS call that fails with a 405 ("Method Not Allowed")

Why do I get this error when the method is handled? And how to fix it?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • https://stackoverflow.com/questions/40985920/making-golang-gorilla-cors-handler-work - Are you sure that preflight is sent for `GET` and `POST`? – Lars Christian Jensen May 03 '21 at 19:02
  • @LarsChristianJensen: yes it is (I checked the headers, and the calls go through from JS). I found the issue and posted an answer. – WoJ May 03 '21 at 19:04

1 Answers1

0

I fixed the issue by updating the CORS() call:

methods := handlers.AllowedMethods([]string{"OPTIONS", "DELETE", "GET", "HEAD", "POST", "PUT", "PATCH"})
origins := handlers.AllowedOrigins([]string{"*"})
headers := handlers.AllowedHeaders([]string{"Content-Type"})
log.Fatal(http.ListenAndServe("127.0.0.42:80", handlers.CORS(methods, origins, headers)(r)))

I think (but I am not sure) that what actually fixed the call is the headers entry.

WoJ
  • 27,165
  • 48
  • 180
  • 345