How to log response and request body in gin

func main() {
    router := gin.New()
    router.Use(UploadRetrievalLog())

    router.GET("/api/v1/ping", func(c *gin.Context) {
			c.String(200, "pong")
		})

    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}
type bodyWriter struct {
	gin.ResponseWriter
	bodyBuf *bytes.Buffer
}

func (w bodyWriter) Write(b []byte) (int, error) {
	//memory copy here!
	w.bodyBuf.Write(b)
	return w.ResponseWriter.Write(b)
}

// UploadRetrievalLog ...
func UploadRetrievalLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		var requestBodyBytes []byte
		if c.Request.Body != nil {
			requestBodyBytes, _ = ioutil.ReadAll(c.Request.Body)
		}
		c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBodyBytes))
		var responseBodyWriter bodyWriter
		//response写缓存
		responseBodyWriter = bodyWriter{
                bodyBuf: bytes.NewBufferString(""),
                ResponseWriter: c.Writer}
		c.Writer = responseBodyWriter
		c.Next()
		responseBody :=strings.Trim(responseBodyWriter.bodyBuf.String(),"\n")      
		//日志持久化逻辑
                //_, err:=service.CreateRetrievalLog(c,api.CreateRetrievalLogRequest{
		//	Operation:  c.Request.Method,
		//	Component:  c.FullPath(),
		//	SourceInfo: string(requestBodyBytes),
		//	SinkInfo:   responseBody,
		//})
		//if err != nil {
		//	c.JSON(http.StatusOK, HTTPGenericResponse{
		//		Code:    http.StatusInternalServerError,
		//		Message: err.Error(),
		//	})
		//	c.Abort()
		//	return
		//}
	}
}

 

你可能感兴趣的:(Go)