camccar
camccar

Reputation: 730

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?

Upvotes: 0

Views: 6084

Answers (2)

Peter
Peter

Reputation: 31771

The Access-Control-Allow-Origin header supports only a single value, so you have to inspect the Origin request header and then make a decision based on that:

package main

import "net/http"

func myHandler(w http.ResponseWriter, r *http.Request) {
    switch origin := r.Header.Get("Origin"); origin {
    case "www.example.com", "example.com":
            w.Header().Set("Access-Control-Allow-Origin", origin)
    }
}

Do note that this header is automatically set in browser's requests and can be set in request performed by other user agents (like curl).

Upvotes: 2

camccar
camccar

Reputation: 730

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.

Upvotes: 6

Related Questions