add cors headers to a http server with a specific origin in go

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.go
func corsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        origin := r.Header.Get("Origin")
        if origin == "http://example.com" { // replace with your origin
            w.Header().Set("Access-Control-Allow-Origin", origin)
            w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
            w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
        }
        if r.Method == "OPTIONS" {
            w.WriteHeader(http.StatusOK)
            return
        }
        next.ServeHTTP(w, r)
    })
}
645 chars
16 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.go
mux := http.NewServeMux()
mux.Handle("/", corsMiddleware(http.HandlerFunc(myHandler)))
http.ListenAndServe(":8080", mux)
121 chars
4 lines

Replace myHandler with your own http.Handler or router instance that handles the incoming requests.

gistlibby LogSnag