2 回答

TA贡献1799条经验 获得超8个赞
该函数采用一个参数,因此您应该能够通过在处理程序中创建一个请求来传递Gin上下文:Transport.RoundTrip*http.Request
func MyHandler(c *gin.Context) {
// passing context to the request
req := http.NewRequestWithContext(c, "GET", "http://localhost:8080", nil)
resp, err := http.DefaultClient.Do(req)
}
请注意,为了能够在不进行其他初始化的情况下使用您覆盖的默认值,应使用 .RoundTripperhttp.DefaultClient

TA贡献1825条经验 获得超6个赞
您可以使用以下命令:
https://github.com/sumit-tembe/gin-requestid
package main
import (
"net/http"
"github.com/gin-gonic/gin"
requestid "github.com/sumit-tembe/gin-requestid"
)
func main() {
// without any middlewares
router := gin.New()
// Middlewares
{
//recovery middleware
router.Use(gin.Recovery())
//middleware which injects a 'RequestID' into the context and header of each request.
router.Use(requestid.RequestID(nil))
//middleware which enhance Gin request logger to include 'RequestID'
router.Use(gin.LoggerWithConfig(requestid.GetLoggerConfig(nil, nil, nil)))
}
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello world!")
})
router.Run(":8080")
}
输出:
[GIN-debug] 2019-12-16T18:50:49+05:30 [bzQg6wTpL4cdZ9bM] - "GET /"
[GIN-debug] 2019-12-16T18:50:49+05:30 [bzQg6wTpL4cdZ9bM] - [::1] "GET / HTTP/1.1 200 22.415µs" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
它还支持自定义请求ID生成器,您可以根据需要进行设计。
- 2 回答
- 0 关注
- 444 浏览
添加回答
举报