Skip to content

Instantly share code, notes, and snippets.

@itcuihao
Last active May 10, 2018 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itcuihao/042e00034447ca1111bfafdbdf945e3c to your computer and use it in GitHub Desktop.
Save itcuihao/042e00034447ca1111bfafdbdf945e3c to your computer and use it in GitHub Desktop.
gin print request and response
```
package router
import (
"aicloud/common"
"bytes"
"io"
"io/ioutil"
"time"
"fmt"
"github.com/gin-gonic/gin"
)
type bodyLog struct {
gin.ResponseWriter
body *bytes.Buffer
}
// Write write
func (w bodyLog) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
// Logger request logger
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
buf, _ := ioutil.ReadAll(c.Request.Body)
b1 := ioutil.NopCloser(bytes.NewBuffer(buf))
b2 := ioutil.NopCloser(bytes.NewBuffer(buf))
uri := c.Request.RequestURI
info := map[string]interface{}{
"type": "REQUEST",
"req": readBody(b1),
"uri": uri,
}
// request
c.Request.Body = b2
// response
bw := &bodyLog{
body: bytes.NewBufferString(""),
ResponseWriter: c.Writer,
}
c.Writer = bw
t := time.Now()
c.Next()
info["Duration"] = time.Since(t).String()
statusCode := c.Writer.Status()
// if statusCode >= 400 {
// info["resp"] = bw.body.String()
// }
info["status"] = statusCode
info["resp"] = bw.body.String()
fmt.Println(info)
}
}
func readBody(r io.Reader) string {
b := new(bytes.Buffer)
b.ReadFrom(r)
return b.String()
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment