Skip to content

Instantly share code, notes, and snippets.

@debnath
Created September 6, 2018 14:52
Show Gist options
  • Save debnath/8a0c630ceb06e626eb409d215a3c6aa8 to your computer and use it in GitHub Desktop.
Save debnath/8a0c630ceb06e626eb409d215a3c6aa8 to your computer and use it in GitHub Desktop.
Echo HandlerFunc for logging all HTTP responses
package middleware
import (
"log"
"net/http"
"github.com/labstack/echo"
)
/*
* This HandlerFunc will log all http responses in the echo framework by intercepting http.ResponseWriter, and logging
* the response before it is sent back to the consumer.
* It might be useful if you are using frameworks/libraries to generate your responses, and do not want to modify its internals.
*
* Example usage:
* e.GET("/graphql", middleware.LogResponseBody(httpHandler)) //Won't need to echo.WrapHandler(httpHandler)) in this case.
*/
//Mimic the interface of http.ResponseWriter, so we can capture the body and parse it.
type LogResponseWriter struct {
w http.ResponseWriter
}
func (w *LogResponseWriter) Header() http.Header {
return w.w.Header()
}
func (w *LogResponseWriter) Write(b []byte) (int, error) {
log.Println("HTTP response body: ", string(b))
return w.w.Write(b)
}
func (w *LogResponseWriter) WriteHeader(h int) {
log.Println("HTTP response header: ", h)
w.w.WriteHeader(h)
}
func LogResponseBody(h http.Handler) echo.HandlerFunc {
return func(c echo.Context) error {
w := &LogResponseWriter{c.Response()}
h.ServeHTTP(w, c.Request())
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment