To add CORS headers to an HTTP server in Go, we can use the cors
middleware package provided by the handlers
package.
Here is an example of how to use it:
main.go491 chars23 lines
In this example, we create an HTTP server using the http
package's NewServeMux()
function. We then add our HTTP routes to the router.
Next, we create the CORS middleware using the handlers.CORS()
function. We specify the allowed origins as an array of strings that contain the hostnames of our client application. We also specify the allowed methods as an array of strings that contain the HTTP request methods that we want to allow.
Finally, we wrap our HTTP server with the CORS middleware using the http.ListenAndServe()
function. The first argument is the TCP address to listen on, and the second argument is the wrapped http.Handler
returned by the cors(router)
function call.
With this setup, any HTTP requests made to our server from the https://my-client.com
origin will include the appropriate CORS headers in their response. Other origins will receive an error response instead.
gistlibby LogSnag