Enable CORS in Golang

I use gorilla/mux package to build Go RESTful API server, and client use JavaScript Request can work,

My Go Server runs at localhost:9091, and the Server code:

router := mux.NewRouter()
//api route is /people, 
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeopleAPI).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))

I find giving OPTIONS here is important, otherwise error will occur:

OPTIONS http://localhost:9091/people 405 (Method Not Allowed)

Failed to load http://localhost:9091/people: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:9092‘ is therefore not allowed access. The response had HTTP status code 405.

after allow OPTIONS it works great. I get the idea from This Article.

Besides, MDN CORS doc mention:

Additionally, for HTTP request methods that can cause side-effects on server’s data, the specification mandates that browsers “preflight” the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method.

Following is the api GetPeopleAPI method, note in the method I give comment //Allow CORS here By * or specific origin, I have another similar answer explaining the concept of CORS Here:

func GetPeopleAPI(w http.ResponseWriter, r *http.Request) {

    //Allow CORS here By * or specific origin
    w.Header().Set("Access-Control-Allow-Origin", "*")

    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    // return "OKOK"
    json.NewEncoder(w).Encode("OKOK")
}

In the client, I use html with javascript on localhost:9092, and javascript will send request to server from localhost:9092

function GetPeople() {
    try {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "http://localhost:9091/people", false);
        xhttp.setRequestHeader("Content-type", "text/html");
        xhttp.send();
        var response = JSON.parse(xhttp.response);
        alert(xhttp.response);
    } catch (error) {
        alert(error.message);
    }
}

and the request can successfully get response "OKOK" .

You can also check response/request header information by tools like Fiddler .

Leave a Comment