go - Preflight issue with http POST in golang -
i using mux package , have code:
func saveconfig(w http.responsewriter, r *http.request) { if origin := r.header.get("origin"); origin != "" { w.header().set("access-control-allow-origin", origin) fmt.println("origin: " + origin) w.header().set("access-control-allow-methods", "post, get, options, put, delete") w.header().set("access-control-allow-headers", "accept, content-type, content-length, accept-encoding, x-csrf-token, authorization") } // stop here if preflighted options request if r.method == "options" { return } body, err := ioutil.readall(io.limitreader(r.body, 1048576)) if err != nil { fmt.println("error: %s\n", err) w.writeheader(http.statusinternalservererror) return } fmt.println("json body:" + string(body)) if err := r.body.close(); err != nil { panic(err) } w.writeheader(http.statuscreated) }
it's working fine on ie chrome preflight sending options method , getting 404 response back. appreciated.
the code registers post, not options. 1 approach change code following:
func newrouter() *mux.router { router := mux.newrouter().strictslash(true) _, route := range routes { var handler http.handler handler = route.handlerfunc handler = commonlibrary.logger(handler, route.name) return router.methods(route.method, "options").path(route.pattern).name(route.name).handler(handler) }
this add options handlers. approach change route method field methods []string
, create router as:
return router.methods(route.methods..., "options").path(route.pattern).name(route.name).handler(handler)
this allow add options subset of handlers.
yet approach register separate handler options:
route{"saveconfig", "options", "/saveconfig", preflight}
Comments
Post a Comment