Search code examples
httpgocors

golang http allow certain domain name both with www and without


I have a golang api I'm writting. I use the following function for cors

func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.WriteHeader(code)
    w.Write(json)
}

This allows my api to be accessible by anyone. I would like to limit it to my domain name. Because that sounds more secure. Lets call it www.example.com

I can Change it to

 w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com")

And this will allow me to make calls when the url is www.example.com but not example.com

I can then change it to

w.Header().Set("Access-Control-Allow-Origin", "http://example.com")

Now I can access my api from example.com but not www.example.com

Adding both does not work Neither this way

w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com,http://example.com")

Nor This way

w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com")
w.Header().Set("Access-Control-Allow-Origin", "http://example.com")

So, is there a way for me to get the requesting origin? so I can dynamically allow the domain? Is there another way for me to solve this problem?


Solution

  • I found that the Origin information is in the http.Request object. You can get the origin with

    origin := r.Header.Get("Origin");
    

    Assuming you have a object some where like

    r *http.Request
    

    If the object is coming from example.com it will return example.com, likewise www.example.com. You can then test if it is one of these two values as a way to authenticate.