add cors headers to a http server in go

To add CORS headers to your HTTP server in Go, you can use the gorilla/mux package to create a new router and set the appropriate headers.

Here's an example code snippet that adds CORS headers to a HTTP server:

main.go
package main

import (
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()

	// Add CORS headers to all responses
	headers := func(w http.ResponseWriter, req *http.Request) {
		// Allow any origin
		w.Header().Set("Access-Control-Allow-Origin", "*")

		// Allow certain methods
		w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")

		// Allow certain headers
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token")

		// Set the cache control header
		w.Header().Set("Cache-Control", "no-store")

		// Continue processing the request
		if req.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}

		r.ServeHTTP(w, req)
	}

	http.ListenAndServe(":8080", http.HandlerFunc(headers))
}
809 chars
37 lines

In this example, we first create a new mux.Router object. We then define a function called headers that adds the necessary CORS headers to the response, as well as the cache control header. If the request method is OPTIONS, we return a 200 status code to indicate that the preflight request was successful. Finally, we call the ServeHTTP method on the router object to continue processing the request.

Note that the code above allows any origin. In production, you should restrict the origin to only those domains that are allowed to access your server.

related categories

gistlibby LogSnag