4

I'm trying to get the request host from gin context, but the only thing close I've found is Context.ClientIP(). I'm dealing with a dynamic IP, so I'd like to get the host name here instead to check it against an allowed list for setting a CORS header. How do I get the client host name?

Ben Walker
  • 2,037
  • 5
  • 34
  • 56

1 Answers1

3

Since you want to use it for CORS, you can take it from origin header. It is essentially the host of the website the request is coming from. It's not really the client's host. But for CORS you want to use origin. Hence, you set the header Access-Control-Allow-Origin.

origin := c.Request.Header.Get("Origin")

A simple handler, that is allowing CORS, could look like this.

allowList := map[string]bool{
    "https://www.google.com": true,
    "https://www.yahoo.com":  true,
}

r.GET("/", func(c *gin.Context) {
    if origin := c.Request.Header.Get("Origin"); allowList[origin] {
        c.Header("Access-Control-Allow-Origin", origin)
    }
    c.JSON(200, gin.H{"message": "ok"})
})
The Fool
  • 16,715
  • 5
  • 52
  • 86
  • There's insufficient information to determine that the origin header is the answer to the OP's question. The OP may want to predicate the CORS headers on the client's hostname. That's not a good idea, but that may be what they are trying to do. –  Feb 16 '22 at 18:14
  • @Zombo, that doesn't make sense. As explained above. CORS is a browser only thing. No server side program respects it. Therefore, no client will have problems with CORS unless the request is initiated from a webpage, in which case the origin header is correct. – The Fool Feb 16 '22 at 18:18
  • This answer appears to have what I want. The only issue I'm left with is that c.Request.Header["Origin"] appears to be a slice of strings, rather than a string. – Ben Walker Feb 16 '22 at 18:28
  • @BenWalker, you can take the first element of the slice or use Get. I have changed my answer. I did not know if gin is using the standard http.Header. If it's using the standard header, Get is a helper to get the first element from the slice ( or an empty string). https://pkg.go.dev/net/http#Header.Get. – The Fool Feb 16 '22 at 18:36