-
Notifications
You must be signed in to change notification settings - Fork 8.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to use middleware to change requestpath #1867
Comments
Hello @NoGroceries,
|
Hello@dmarkham |
Ok so the request getting to gin looks like If I understand correctly i'm not sure you can do this. By time your running middleware I think the system has already picked a handlerFunc. Maybe someone else has some ideas. |
Is it what you want to do? like url rewrite? import (
"github.com/gin-gonic/gin"
"github.com/golang/glog"
"net/http"
"strings"
)
type SkipContextPathRouter struct {
ContextPath string
Start int
*gin.Engine
}
func (r *SkipContextPathRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.RequestURI, r.ContextPath) {
glog.Infof("request url:%s, will skip prefix:%s", req.RequestURI, r.ContextPath)
// remove context path before gin router process
uri := req.RequestURI[r.Start:]
req.RequestURI = uri
req.URL.Path = req.URL.Path[r.Start:]
}
r.Engine.ServeHTTP(w, req)
}
contextPathToSkip := "/api/v1/"
skipContextPathRouter := &router.SkipContextPathRouter{
ContextPath: contextPathToSkip,
Start: len(contextPathToSkip),
Engine: ginRouter,
}
s := &http.Server{
Addr: ":8080",
Handler: skipContextPathRouter,
MaxHeaderBytes: 1 << 20,
} |
It doesn't work for me as well,
|
I want to trim the common prefix of requestUrl in the middleware ,
if ok :=strings.HasPrefix(requestURI,"/api");ok { c.Request.URL.Path = strings.TrimPrefix(requestURI,"/api") c.Request.RequestURI = strings.TrimPrefix(requestURI,"/api") }
but it don't work
Description
Screenshots
The text was updated successfully, but these errors were encountered: