-
Is there a straightforward way to convert middleware that follows the pattern See:
E.g.: // Decode JWT from an HTTP request.
func AuthMiddleware(log *zerolog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req, err := ExtractTokenWithClaimsIntoRequest(r)
if err == request.ErrNoTokenInRequest {
next.ServeHTTP(w, r)
return
}
if err != nil {
log.Error().Err(err).Msg("Extract token with claims failed")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, req)
})
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hello @gf3, It's easy to conver such middlewares to Iris but if you don't want and you just want to wrap it, then use the app := iris.New()
// ...
loggerMiddleware := AuthMiddleware(logger)
app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
loggerMiddleware(router).ServeHTTP(w, r)
}) Full code example: package main
import (
"context"
"net/http"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
httpThirdPartyWrapper := StandardWrapper(Options{
Message: "test_value",
})
app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
httpThirdPartyWrapper(router).ServeHTTP(w, r)
})
app.Get("/", index)
app.Listen(":8080")
}
func index(ctx iris.Context) {
ctx.Writef("Message: %s\n", ctx.Value(msgContextKey))
}
type Options struct {
Message string
}
type contextKey uint8
var (
msgContextKey contextKey = 1
)
func StandardWrapper(opts Options) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ...
req := r.WithContext(context.WithValue(r.Context(), msgContextKey, opts.Message))
next.ServeHTTP(w, req)
})
}
} |
Beta Was this translation helpful? Give feedback.
-
What is the solution if you want to only apply this middleware on a |
Beta Was this translation helpful? Give feedback.
Hello @gf3,
It's easy to conver such middlewares to Iris but if you don't want and you just want to wrap it, then use the
WrapRouter
, example:Full code example: