Does middleware always run before endpoint handler? #2661
Answered
by
aldas
winston0410
asked this question in
Q&A
-
Reading the documentation, I notice that it didn't mention whether the middleware would only run before handler, or it can be config to run after a handler. Is it correct to say that at v4, middleware would only be triggered before a handler(this is what I found out by logging). Is it possible to run a middleware after a handler, so I can transform the response body(for example, minify the response) |
Beta Was this translation helpful? Give feedback.
Answered by
aldas
Jul 24, 2024
Replies: 1 comment 2 replies
-
You can add your logic "after" part inside middleware. See this example: package main
import (
"errors"
"github.com/labstack/echo/v4"
"log/slog"
"net/http"
"os"
)
func main() {
e := echo.New()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
logger.Info("before calling next middleware/handler")
err := next(c)
logger.Info("after calling next middleware/handler")
return err
}
})
e.GET("/", func(c echo.Context) error {
logger.Info("inside the handler")
return c.String(http.StatusOK, "OK")
})
if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("server closed due to unexpected error", "err", err)
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you might want to check these middlewares how similar things are done