I want use middleware to output the every request Latency ,to reponse header ,like
package main
import (
"time"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(Latency)
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
func Latency(c *gin.Context) {
// Start timer
start := time.Now()
// Process request
c.Next()
// output the http request Latency to response header ,but not working ,how can log the cost time to response header
c.Writer.Header().Set("Latency", time.Now().Sub(start).String())
}
but ,the reponse header not show `Latency',how can i log the Latency to reponse header? thks
Comment From: dtest11
solution
package main
import (
"github.com/gin-gonic/gin"
"time"
)
type XResponseTimer struct {
gin.ResponseWriter
start time.Time
}
func (w *XResponseTimer) WriteHeader(statusCode int) {
duration := time.Now().Sub(w.start)
w.Header().Set("X-Response-Time", duration.String())
w.ResponseWriter.WriteHeader(statusCode)
}
func (w *XResponseTimer) Write(b []byte) (int, error) {
return w.ResponseWriter.Write(b)
}
func NewXResponseTimer(c *gin.Context) {
blw := &XResponseTimer{ResponseWriter: c.Writer, start: time.Now()}
c.Writer = blw
c.Next()
}
func main() {
r := gin.Default()
r.Use(NewXResponseTimer)
r.Use(func(context *gin.Context) {
//time.Sleep(1 * time.Second)
context.Next()
})
r.GET("/", func(c *gin.Context) {
time.Sleep(10 * time.Millisecond)
c.JSON(200, gin.H{
"message": "pong",
})
})
//go browser.OpenURL("http://localhost:8080/")
err := r.Run()
if err != nil {
panic(err)
} // listen and serve on 0.0.0.0:8080
}
reponse
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Response-Time: 10.314678ms
Date: Tue, 26 Jul 2022 15:25:55 GMT
Content-Length: 18
{"message":"pong"}
Comment From: dtest11
https://github.com/dtest11/reponse/blob/1f462b27a8930673eb85868e1bdc402a488693db/reponse_time_test.go#L8