julienschmidt / httprouter

A high performance HTTP request router that scales well
https://pkg.go.dev/github.com/julienschmidt/httprouter
BSD 3-Clause "New" or "Revised" License
16.64k stars 1.47k forks source link

Feature request: allow setting allowed origin #214

Closed dimhoLt closed 5 years ago

dimhoLt commented 7 years ago

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-Origins, 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 the OPTIONS-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.

  1. Alongside the HandleOPTIONS-setting, add an AllowedOrigins []string-setting which, if not empty, sends the Access-Control-Allow-Origin-header with its data.

  2. On the router, add a method such as GetRegisteredMethods(path string) []string, or similar, returning an array of http.Method*-constants which can be easily strings.Join-ed into a custom Allow or Access-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.

cristiangraz commented 7 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

julienschmidt commented 5 years ago

See Automatic OPTIONS responses and CORS