Closed dimhoLt closed 5 years ago
You can implement this yourself pretty simply -- we have a "framework" that standardizes multiple routers to add router groups, upstream/downstream middleware, context, CORS support, etc -- and implemented this exact thing for several routers. Most of the routers provide a way for you to match a path/HTTP method so you can create your own list of allowed routes to respond to CORS/OPTIONS requests.. You can see an example that has been working well for us here: https://github.com/cristiangraz/kumi/blob/master/router/httprouter.go#L54-L65
Hello!
I'm using the router for my RESTful JSON API, and intended to use the built-in options handler.
However, the built-in OPTIONS-handler is not aware of
Access-Control-Allowed-Origin
s, making it meaningless for CORS-safe browsers. This means that if you are going to use the API with such browsers, you will have to build your own implementation of theOPTIONS
-handler.This would be fine, as it's a simple method, except that you no longer know which methods have registered handlers, and since the
root
-object is (correctly) not exported there's no way to extract this.Solutions There are, in my opinion, two potential solutions to this problem.
Alongside the
HandleOPTIONS
-setting, add anAllowedOrigins []string
-setting which, if not empty, sends theAccess-Control-Allow-Origin
-header with its data.On the router, add a method such as
GetRegisteredMethods(path string) []string
, or similar, returning an array ofhttp.Method*
-constants which can be easilystrings.Join
-ed into a customAllow
orAccess-Control-Allow-Methods
header, enabling a complete custom OPTIONS-handler.I prefer the first option, as I believe it simply completes the
HandleOPTIONS
-setting which already exists.