Trailing slash in subrouter #111
Answered
by
vearutop
pboguslawski
asked this question in
Q&A
-
When using chi wrapper with subrouter defined in separate package like this...
...it is possible to call it with or without trailing slash i.e. In such scenario |
Beta Was this translation helpful? Give feedback.
Answered by
vearutop
Jan 16, 2023
Replies: 1 comment 1 reply
-
Hello, it is possible with additional wrap that overrides route info of a handler, please check an example: package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/swaggest/assertjson"
"github.com/swaggest/rest"
"github.com/swaggest/rest/chirouter"
"github.com/swaggest/rest/nethttp"
"github.com/swaggest/rest/web"
swgui "github.com/swaggest/swgui/v4emb"
"github.com/swaggest/usecase"
)
func dummy() usecase.Interactor {
return usecase.NewInteractor(func(ctx context.Context, input struct{}, output *struct{}) error {
println("dummy")
return nil
})
}
func main() {
service := web.DefaultService()
service.Route("/test", func(r chi.Router) {
r.(*chirouter.Wrapper).Wrap(func(handler http.Handler) http.Handler {
var h rest.HandlerWithRoute
if nethttp.HandlerAs(handler, &h) {
if h.RoutePattern() == "/test/" {
handler = nethttp.HandlerWithRouteMiddleware(h.RouteMethod(), "/test")(handler)
}
// Or a more general trimmer.
//handler = nethttp.HandlerWithRouteMiddleware(h.RouteMethod(), strings.TrimRight(h.RoutePattern(), "/"))(handler)
}
return handler
})
r.Method(http.MethodGet, "/", nethttp.NewHandler(dummy()))
})
spec, _ := assertjson.MarshalIndentCompact(service.OpenAPI, "", " ", 80)
fmt.Println(string(spec))
service.Docs("/docs", swgui.New)
fmt.Println("Swagger UI at http://localhost:8010/docs.")
if err := http.ListenAndServe("localhost:8010", service); err != nil {
log.Fatal(err)
}
} {
"openapi":"3.0.3","info":{"title":"","version":""},
"paths":{
"/test":{
"get":{
"summary":"Dummy","operationId":"dummy",
"responses":{"204":{"description":"No Content"}}
}
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
pboguslawski
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, it is possible with additional wrap that overrides route info of a handler, please check an example: