How to get request host from Go gin context?

Issue

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?

Solution

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"})
})

Answered By – The Fool

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.