Last active
October 24, 2022 18:40
-
-
Save yanmhlv/65013b88ce386890bc585234a4820d4f to your computer and use it in GitHub Desktop.
logging body middleware for labstack/echo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"io/ioutil" | |
"github.com/labstack/echo" | |
"github.com/labstack/echo/engine/standard" | |
mw "github.com/labstack/echo/middleware" | |
) | |
func logBodyMiddleware(next echo.HandlerFunc) echo.HandlerFunc { | |
return func(c echo.Context) error { | |
if c.Request().Header().Get("Content-Type") != echo.MIMEApplicationJSON { | |
return next(c) | |
} | |
data, err := ioutil.ReadAll(c.Request().Body()) | |
if err != nil { | |
return err | |
} | |
c.Logger().Error(string(data)) | |
c.Request().SetBody(bytes.NewReader(data)) | |
return next(c) | |
} | |
} | |
func main() { | |
e := echo.New() | |
e.Use( | |
mw.Recover(), | |
//mw.Logger(), | |
logBodyMiddleware, | |
) | |
e.Post("/", func(c echo.Context) error { | |
result := struct { | |
Message string `json:"message"` | |
}{} | |
if err := c.Bind(&result); err != nil { | |
return err | |
} | |
return c.JSON(200, result) | |
}) | |
e.Run(standard.New(":3000")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For echo v4: