yousuf64 / shift Goto Github PK
View Code? Open in Web Editor NEWHigh-performance HTTP router for Go.
License: MIT License
High-performance HTTP router for Go.
License: MIT License
I've observed unexpected behavior in route matching when having empty parameter values in the URL.
/products:id
/products/:id/tags
The following routes match with /products:id
when they shouldn't match any.
/products/
/products/1
/products//
/products//tags
/posts/:id
/:abc
/:abc/:xyz/comments
The following routes match with /posts/:id
when they shouldn't match any.
/posts//
/posts//comments
/:aaa
The following routes match with /:aaa
when they shouldn't match any.
https://example.com//
https://example.com///
https://example.com///hello
TrailingSlashMatch
: Skip
PathCorrectionMatch
: Skip
Hello @yousuf64
Awesome library, many thanks for working on it! Please take a look at this test:
func TestParams_Copy(t *testing.T) {
t.Run("Copy should not be affected when source is reset and reused", func(t *testing.T) {
p := newParams(1)
p.setKeys(&[]string{"foo"})
p.appendValue("bar")
cp := p.Copy()
p.reset()
p.setKeys(&[]string{"foo"})
p.appendValue("bar2")
val := cp.Get("foo")
assert(t, val == "bar", fmt.Sprintf("expected: bar, got: %s", val))
})
}
Outputs expected: bar, got: bar2
Slices in copy still reference to the original ones. If I am not missing sth here โ pooling params and re-using them may result in copy corruption at the moment.
Hello again @yousuf64
Consider this test case:
func TestRouter_ServeHTTP_ParamRoutes_New(t *testing.T) {
r := newTestShift()
paths := map[string]string{
"/:file": http.MethodGet,
"/hero-:name": http.MethodGet,
}
rec := &recorder{}
for path, meth := range paths {
r.Map([]string{meth}, path, rec.Handler(path))
}
tt := routerScenario{
{method: http.MethodGet, path: "/hero-", valid: false, pathTemplate: "", params: nil},
}
testRouter_ServeHTTP(t, r.Serve(), rec, tt)
}
It passes. Now add one more route /hero/:name
(which I suppose should not affect test case):
func TestRouter_ServeHTTP_ParamRoutes_New(t *testing.T) {
r := newTestShift()
paths := map[string]string{
"/:file": http.MethodGet,
"/hero-:name": http.MethodGet,
"/hero/:name": http.MethodGet,
}
rec := &recorder{}
for path, meth := range paths {
r.Map([]string{meth}, path, rec.Handler(path))
}
tt := routerScenario{
{method: http.MethodGet, path: "/hero-", valid: false, pathTemplate: "", params: nil},
}
testRouter_ServeHTTP(t, r.Serve(), rec, tt)
}
As we can see now /hero-
starting to match /:file
route:
router_test.go:2106: /hero- > didn't expect a handler, but found a handler with template '/:file'
Which actually seems correct, but in the first test it did not match for some reason.
No middleware
is ran if the route does not exist.
This also means the heartbeat
middleware
endpoint never works.
func main() {
router := shift.New()
router.UseTrailingSlashMatch(shift.WithExecute())
router.Use(authMiddleware)
router.Use(heartbeat("/ping"))
router.Use(shift.Recover())
router.GET("/", shift.HTTPHandlerFunc(HelloHandler))
router.GET("/other", func(w http.ResponseWriter, r *http.Request, route shift.Route) error {
_, err := fmt.Fprint(w, "Hello, world!")
return err
})
http.ListenAndServe(":8080", router.Serve())
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "๐๐๐")
}
func authMiddleware(next shift.HandlerFunc) shift.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, route shift.Route) error {
if v := r.Header.Get("Authorization"); v != "" {
return next(w, r, route)
}
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("'Authorization' header required"))
return errors.New("'Authorization' header required")
}
}
func heartbeat(endpoint string) shift.MiddlewareFunc {
log.Println("inside hb")
return func(next shift.HandlerFunc) shift.HandlerFunc {
log.Println("inside next")
return func(w http.ResponseWriter, r *http.Request, route shift.Route) error {
log.Println("urlpath", r.URL.Path)
if (r.Method == "GET" || r.Method == "HEAD") && strings.EqualFold(r.URL.Path, endpoint) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("."))
}
return next(w, r, route)
}
}
}
I think this would be good since chi
and shift
are similar being router & middleware
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.