To add CORS (Cross-Origin Resource Sharing) headers to a Go HTTP server with a specific origin, you can write a middleware that adds the headers to the response.
Here is an example middleware that adds the necessary headers:
main.go645 chars16 lines
This middleware checks the Origin
header of the request and only adds the CORS headers if the origin matches the specified value (http://example.com
in this example). If the request method is OPTIONS
, it sends a response with status code 200 and returns early, allowing the browser to make the actual cross-origin request.
To use this middleware with your HTTP server, wrap your router or handler function with it:
main.go121 chars4 lines
Replace myHandler
with your own http.Handler or router instance that handles the incoming requests.
gistlibby LogSnag