Skip to content

Instantly share code, notes, and snippets.

@lufia
Created November 14, 2017 10:19
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 lufia/7c5411ef88fa83b99400d1b92add7b8e to your computer and use it in GitHub Desktop.
Save lufia/7c5411ef88fa83b99400d1b92add7b8e to your computer and use it in GitHub Desktop.
verbose logger for gin framework
type responseWriter struct {
gin.ResponseWriter
buf bytes.Buffer
}
func (w *responseWriter) Write(b []byte) (int, error) {
w.buf.Write(b)
return w.ResponseWriter.Write(b)
}
func (w *responseWriter) Body() []byte {
return w.buf.Bytes()
}
type requestReader struct {
body io.ReadCloser
buf bytes.Buffer
}
func (r *requestReader) Read(p []byte) (int, error) {
n, err := r.body.Read(p)
r.buf.Write(p[0:n])
return n, err
}
func (r *requestReader) Close() error {
return r.body.Close()
}
func VerboseLogger(w io.Writer) gin.HandlerFunc {
return func(c *gin.Context) {
p := responseWriter{
ResponseWriter: c.Writer,
}
c.Writer = &p
r := requestReader{body: c.Request.Body}
c.Request.Body = &r
c.Next()
if s := c.GetHeader("Content-Type"); s != "" {
fmt.Fprintln(w, "< Content-Type:", s)
}
if r.buf.Len() > 0 {
fmt.Fprintf(w, "< %s\n", r.buf.Bytes())
}
if s := p.Header().Get("Content-Type"); s != "" {
fmt.Fprintln(w, "> Content-Type:", s)
}
if body := p.Body(); len(body) > 0 {
fmt.Fprintf(w, "> %s\n", body)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment