Correct process for setting up CORS

Hello! I’m trying to test out CORS using the http package. I want to enable localhost:8081 to only have GET access (my go server is on localhost:8080). I can access the endpoint fine from localhost:8081 by making a get request. But I can still access it by doing a post request. I guess that makes sense since in the handler I’m giving the “You got access!” response at the end. But does this mean that I need to explicitly check the the method of the request and then reject it if it’s anything other than a GET or OPTIONS? Would that be the right way to go about this?

package main

import "net/http"

func main() {
    http.HandleFunc("/", reqHandler)
    http.ListenAndServe(":8080", nil)
}

func reqHandler(w http.ResponseWriter, r *http.Request) {
    // allow requests from localhost:8081
    w.Header().Add("Access-Control-Allow-Origin", "http://localhost:8081")

    // only allow get method
    w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")

    w.Write([]byte("You got access!"))
}

A good way to do this is to use gorilla/mux toolkit and set up the headers for CORS on middleware. See an example bellow.

Yes, for example using only the standard library:

func reqHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)

		return
    }

   ...
}

And for the CORS headers, you could define them in a middleware that will be used in every request like:

func corsMiddleware(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Add("Access-Control-Allow-Origin", "http://localhost:8081")
        w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")

		h.ServeHTTP(w, r)
	}
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", reqHandler)
    http.ListenAndServe(":8080", corsMiddleware(mux))
}
1 Like

Thanks, this looks similar to Express from Node which I’m used to. Will explore this option as well as just using the std lib.

Thank you very much! The middleware option is super useful.