5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-15 09:50:27 +00:00
matterbridge/vendor/github.com/labstack/echo/v4/middleware/body_dump.go

107 lines
2.4 KiB
Go
Raw Normal View History

2017-12-07 22:00:56 +00:00
package middleware
import (
"bufio"
"bytes"
"io"
2017-12-07 22:00:56 +00:00
"net"
"net/http"
"github.com/labstack/echo/v4"
2017-12-07 22:00:56 +00:00
)
type (
// BodyDumpConfig defines the config for BodyDump middleware.
BodyDumpConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Handler receives request and response payload.
// Required.
Handler BodyDumpHandler
}
// BodyDumpHandler receives the request and response payload.
BodyDumpHandler func(echo.Context, []byte, []byte)
bodyDumpResponseWriter struct {
io.Writer
http.ResponseWriter
}
)
var (
2018-02-20 23:48:10 +00:00
// DefaultBodyDumpConfig is the default BodyDump middleware config.
2017-12-07 22:00:56 +00:00
DefaultBodyDumpConfig = BodyDumpConfig{
Skipper: DefaultSkipper,
}
)
// BodyDump returns a BodyDump middleware.
//
2020-01-09 20:02:56 +00:00
// BodyDump middleware captures the request and response payload and calls the
2017-12-07 22:00:56 +00:00
// registered handler.
func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc {
c := DefaultBodyDumpConfig
c.Handler = handler
return BodyDumpWithConfig(c)
}
// BodyDumpWithConfig returns a BodyDump middleware with config.
// See: `BodyDump()`.
func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc {
// Defaults
if config.Handler == nil {
panic("echo: body-dump middleware requires a handler function")
}
if config.Skipper == nil {
config.Skipper = DefaultBodyDumpConfig.Skipper
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next(c)
}
// Request
reqBody := []byte{}
if c.Request().Body != nil { // Read
2023-01-28 21:57:53 +00:00
reqBody, _ = io.ReadAll(c.Request().Body)
2017-12-07 22:00:56 +00:00
}
2023-01-28 21:57:53 +00:00
c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) // Reset
2017-12-07 22:00:56 +00:00
// Response
resBody := new(bytes.Buffer)
mw := io.MultiWriter(c.Response().Writer, resBody)
writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}
c.Response().Writer = writer
if err = next(c); err != nil {
c.Error(err)
}
// Callback
config.Handler(c, reqBody, resBody.Bytes())
return
}
}
}
func (w *bodyDumpResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
}
func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func (w *bodyDumpResponseWriter) Flush() {
w.ResponseWriter.(http.Flusher).Flush()
}
func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}