2 回答

TA貢獻1799條經(jīng)驗 獲得超8個贊
該函數(shù)采用一個參數(shù),因此您應(yīng)該能夠通過在處理程序中創(chuàng)建一個請求來傳遞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)
}
請注意,為了能夠在不進行其他初始化的情況下使用您覆蓋的默認值,應(yīng)使用 .RoundTripperhttp.DefaultClient

TA貢獻1825條經(jīng)驗 獲得超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生成器,您可以根據(jù)需要進行設(shè)計。
- 2 回答
- 0 關(guān)注
- 442 瀏覽
添加回答
舉報