如何从Go gin上下文中获取请求的主机名?

huangapple go评论73阅读模式
英文:

How to get request host from Go gin context?

问题

我正在尝试从gin上下文中获取请求的主机名,但我找到的唯一接近的方法是Context.ClientIP()。由于我处理的是动态IP,所以我想在这里获取主机名,以便将其与允许列表进行检查,以设置CORS头。我该如何获取客户端的主机名?

英文:

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?

答案1

得分: 3

由于您想将其用于CORS,您可以从origin头中获取它。它实际上是请求来源网站的主机。它并不是真正的客户端主机。但是对于CORS,您希望使用origin。因此,您设置了头部Access-Control-Allow-Origin

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

一个简单的允许CORS的处理程序可能如下所示。

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"})
})
英文:

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

huangapple
  • 本文由 发表于 2022年2月17日 01:30:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/71146582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定