我正在使用 Go 的 Gin Web 框架创建一个端点。我的处理函数中需要完整的服务器 URL。例如,如果服务器正在运行http://localhost:8080并且我的端点是,那么当调用我的处理程序时/foo我需要。http://localhost:8080/foo
如果有人熟悉 Python 的快速 API,该对象有一个具有完全相同功能的Request方法:https: //stackoverflow.com/a/63682957/5353128url_for(<endpoint_name>)
在 Go 中,我尝试访问context.FullPath(),但只返回我的端点/foo,而不返回完整的 URL。除此之外,我在文档中找不到合适的方法:https://pkg.go.dev/github.com/gin-gonic/gin#Context
那么这可以通过gin.Context对象本身实现吗?还是还有其他方法?我对 Go 完全陌生。
Nic*_*ick 16
c.Request.Host+c.Request.URL.Path应该可行,但必须确定方案。
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/foo", func(c *gin.Context) {
fmt.Println("The URL: ", c.Request.Host+c.Request.URL.Path)
})
r.Run(":8080")
}
Run Code Online (Sandbox Code Playgroud)
您可以确定您可能已经知道的方案。但你可以检查如下:
scheme := "http"
if c.Request.TLS != nil {
scheme = "https"
}
Run Code Online (Sandbox Code Playgroud)
如果您的服务器位于代理后面,您可以通过以下方式获取方案c.Request.Header.Get("X-Forwarded-Proto")
| 归档时间: |
|
| 查看次数: |
19079 次 |
| 最近记录: |