Git Product home page Git Product logo

fasthttprouter's People

Contributors

abiosoft avatar bbrodriges avatar buaazp avatar chaahk avatar corneldamian avatar da-z avatar dahankzter avatar dlsniper avatar eaglerayp avatar farmergreg avatar javierprovecho avatar jjeffery avatar julienschmidt avatar kamronbatman avatar lhigueragamboa avatar mdanzinger avatar mhor avatar nothingmuch avatar oov avatar peterldowns avatar philippfranke avatar preetam avatar readmecritic avatar rogpeppe avatar tcyrus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fasthttprouter's Issues

panic: runtime error: index out of range

panic: runtime error: index out of range

goroutine 147315753 [running]:
panic(0x779ae0, 0xc42000c110)
	/gaodun/dist/go/src/runtime/panic.go:500 +0x1a1
github.com/valyala/fasthttp.decodeArgAppend(0xc429e41800, 0x13f, 0x400, 0xc42ddcd000, 0x1d6, 0x400, 0xc42fcf9201, 0xc42fcf9287, 0x1, 0xb)
	/gaodun/test/src/github.com/valyala/fasthttp/args.go:454 +0x1ea
github.com/valyala/fasthttp.decodeArg(0xc429e41800, 0x20b, 0x400, 0xc42ddcd000, 0x1d6, 0x400, 0x1, 0xc42fcf9290, 0xc42fcf9290, 0xc42c9cda60)
	/gaodun/test/src/github.com/valyala/fasthttp/args.go:444 +0x72
github.com/valyala/fasthttp.(*argsScanner).next(0xc42c9cd9c8, 0xc42ba94a80, 0x7)
	/gaodun/test/src/github.com/valyala/fasthttp/args.go:423 +0x353
github.com/valyala/fasthttp.(*Args).ParseBytes(0xc430506f98, 0xc42ddcd000, 0x23d, 0x400)
	/gaodun/test/src/github.com/valyala/fasthttp/args.go:89 +0x106
github.com/valyala/fasthttp.(*Request).parsePostArgs(0xc430506d80)
	/gaodun/test/src/github.com/valyala/fasthttp/http.go:665 +0xcf
github.com/valyala/fasthttp.(*Request).PostArgs(0xc430506d80, 0x1)
	/gaodun/test/src/github.com/valyala/fasthttp/http.go:652 +0x2b
github.com/valyala/fasthttp.(*RequestCtx).PostArgs(0xc430506d80, 0x4)
	/gaodun/test/src/github.com/valyala/fasthttp/server.go:694 +0x2d
main.envRequestHandler(0xc430506d80)
	/home/gitlab-runner/builds/1bd35413/0/devops/lisa-api/main.go:259 +0x2ee
github.com/buaazp/fasthttprouter.(*Router).Handler(0xc420011260, 0xc430506d80)
	/gaodun/test/src/github.com/buaazp/fasthttprouter/router.go:300 +0xad5
github.com/buaazp/fasthttprouter.(*Router).Handler-fm(0xc430506d80)
	/home/gitlab-runner/builds/1bd35413/0/devops/lisa-api/main.go:302 +0x34
github.com/valyala/fasthttp.(*Server).serveConn(0xc420094500, 0x988140, 0xc42dbb3fe8, 0xc420088401, 0xc420080101)
	/gaodun/test/src/github.com/valyala/fasthttp/server.go:1547 +0x588
github.com/valyala/fasthttp.(*Server).(github.com/valyala/fasthttp.serveConn)-fm(0x988140, 0xc42dbb3fe8, 0xc42c9cdf38, 0x1)
	/gaodun/test/src/github.com/valyala/fasthttp/server.go:1261 +0x3e
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc420088480, 0xc4300837c0)
	/gaodun/test/src/github.com/valyala/fasthttp/workerpool.go:210 +0xde
github.com/valyala/fasthttp.(*workerPool).getCh.func1(0xc420088480, 0xc4300837c0, 0x74b6e0, 0xc4300837c0)
	/gaodun/test/src/github.com/valyala/fasthttp/workerpool.go:182 +0x35
created by github.com/valyala/fasthttp.(*workerPool).getCh
	/gaodun/test/src/github.com/valyala/fasthttp/workerpool.go:184 +0x111

Occasionally working route

Hello!
I've got some crazy shit here: my fasthttprouter handler works sometimes.

Here's an example to get the idea:

func Test(ctx *fasthttp.RequestCtx) {
	ctx.WriteString(ctx.UserValue("test").(string) + "\n")
}
...
router.GET("/test/:test", Test)
# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah^C
# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah
blah
# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah
blah
# curl http://127.0.0.1:8080/test/blah
Not Found# curl http://127.0.0.1:8080/test/blah
blah

So, sometimes it routes the request to the handler and sometimes it doesn't - throws 404.
As far as i can see this happens only with named variables like ":test" here, the usual stuff works well.

Any ideas? Thanks in advance!

file server

I'm using Parseglobe and ExecuteTemplate with ctx. However, I need to setup fileserver where each html, css, and img file get their respective header (such as text/html, text/css, image/jpg etc) so that they don't show up as a plain text. I tried the following code but failed. Any help would he appreciated :)

package main

import (
"html/template"
"log"
"github.com/valyala/fasthttp"
)
func init() {
	tpl = template.Must(template.ParseGlob("public/templates/*.html"))
}

func main() {
m := func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Path()) {
		case "/":
			idx(ctx)
		default:
			ctx.Error("not found", fasthttp.StatusNotFound)
		}

	}
	if err := fasthttp.ListenAndServe(":8081", m); err != nil {
		log.Fatalf("Error in server: %s", err)
	}
}

func idx(ctx *fasthttp.RequestCtx) { 

path := ctx.Path()
	switch {
	case bytes.HasPrefix(path, imgPrefix):
		ctx.SetContentType("image/jpeg")
	case bytes.HasPrefix(path, cssPrefix):
		ctx.SetContentType("text/css")
	default:
		ctx.SetContentType("text/css")
	}

err := tpl.ExecuteTemplate(ctx, "index.html",pd)
	if err != nil {
		log.Println("LOGGED", err)
	//	ctx.Error("Internal server error", ctx.StatusInternalServerError)
		return
	}

New upstream commits

There are multiple:

  • Native OPTIONS header
  • Better unicode upper/lowerase normalization
  • Send "allow headers" on 405
  • There are some new README changes; IDK if you want these to be updated downstream

How do you want to merge downstream? I was thinking about cherry-picking like this....

git remote add julienschmidt https://github.com/julienschmidt/httprouter
git fetch --all
git cherry-pick -n [commit_hash]
# Fix merge conflicts
git commit -m "Cherry pick [commit_hash]"

...but that would leave the source tree messy. Thoughts?

Handling subdomains

How this library can handle subdomains like cloud.dmester.xyz or similar?
Or directly domains like dmester.xyz or librelabua.org in the same program without needing reverse proxy or similar.

Is the example working?

I've tried the example from the README.md:

package main

import (
        "fmt"
        "log"

        "github.com/buaazp/fasthttprouter"
        "github.com/valyala/fasthttp"
)

func Index(ctx *fasthttp.RequestCtx) {
        fmt.Fprint(ctx, "Welcome!\n")
}

func Hello(ctx *fasthttp.RequestCtx) {
        fmt.Fprintf(ctx, "hello, %s!\n", ctx.UserValue("name"))
}

func main() {
        router := fasthttprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)

        log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}

When I run it, it shows:

./test.go:21: cannot use Index (type func(*fasthttp.RequestCtx)) as type fasthttprouter.Handle in argument to router.GET
./test.go:22: cannot use Hello (type func(*fasthttp.RequestCtx)) as type fasthttprouter.Handle in argument to router.GET

Converto type interface to int

I want to get integer value: var id = c.UserValue("id") but i got this error : cannot convert c.UserValue("id") (type interface {}) to type int: need type assertion
what should I do? Thanks

Add Group and Middleware support

Hello contributors,

I am looking for something like this

router.Use(MiddlewareFunction)

and

api = router.Group("/api")
api.Use(APIMiddleware)
api.GET("/", handle)

Can you add this features?
Thanks.

body size exceeds the given limit

2017/03/27 16:12:59 error when serving connection "127.0.0.1:8083"<->"127.0.0.1:35588": body size exceeds the given limit

I got those error when uploading a big picture, how to set maxRequestBodySize?

How to init fake RequestCtx for unit test's?

Good day,
For unit testing need somehow make face RequestCtx struct to use it in testing router handler?
The question: how make it nice and easy, maybe already somebody have made router handler's functions test?

wildcard route ':id' conflicts with existing children in path

I have the following routers, but when I run the program I see the next error

r.POST("/user/actions/search", s)
r.POST("/user/:id/collections/relations", addR)
r.DELETE("/user/:id/collections/relations", removeR)
r.GET("/user/:id", g)
r.POST("/user", a)
r.DELETE("/user/:id",d)
panic: wildcard route ':id' conflicts with existing children in path '/user/:id/collections/relations'

goroutine 1 [running]:
panic(0x29b840, 0xc420138540)
        /usr/local/go/src/runtime/panic.go:500 +0x1a1
github.com/buaazp/fasthttprouter.(*node).insertChild(0xc420012230, 0xc42004fb01, 0x31193c, 0x19, 0x311933, 0x22, 0xc4313d3410)
        /Users/user/go/src/github.com/buaazp/fasthttprouter/tree.go:237 +0xc27
github.com/buaazp/fasthttprouter.(*node).addRoute(0xc420012230, 0x311933, 0x22, 0xc4313d3410)
        /Users/user/go/src/github.com/buaazp/fasthttprouter/tree.go:193 +0x217
github.com/buaazp/fasthttprouter.(*Router).Handle(0xc4313d3320, 0x3040b0, 0x4, 0x311933, 0x22, 0xc4313d3410)
        /Users/user/go/src/github.com/buaazp/fasthttprouter/router.go:210 +0xcc
github.com/buaazp/fasthttprouter.(*Router).POST(0xc4313d3320, 0x311933, 0x22, 0xc4313d3410)
        /Users/user/go/src/github.com/buaazp/fasthttprouter/router.go:169 +0x5e

Serve embedded files?

Is it possible to serve embedded static files? I'd like to be able to embed my static files with go-bindata and then serve them using fasthttp and fasthttprouter, but can't seem to figure out if it is possible.
Thanks

How to update a route path?

Hi, I know that Tree.addRoute is for adding a new route, what if I want to remove an existing route or change the handler of an existing route? Is there public/official func for them?

Integrate with gorilla/websocket

Is it possible to use gorilla/websocket with this library ?

I could not figure out the way to get http.ResponseWriter, and *http.Request.

Parameters as request instead of endpoint url

Hi

I have followed the examples and defined a router like this:

router.GET("/customer/account/detail/:accountId", myHandler.customerAccountDetailHandler)

And call to my service as http://locahost:9296/customer/account/detail/2

But I realised that I do not want to have the parameters as part of the endpoint , I rather prefer to use normal parameters by calling my service like this:

http://locahost:9296/customer/account/detail?accountId=2

Is it possible to be done with fasthttprouter? How?

Thanks in advance
J

wildcard route ':slug' conflicts with existing children

I am using this code to implement a router, the openapi spec is given by my mentor so routes are not to be changed

type Route struct {
	Name    string
	Method  string
	Path    string
	Handler fasthttp.RequestHandler
}

type Routes []Route

func NewRouter() *fasthttprouter.Router {
	router := fasthttprouter.New()
	for _, route := range routes {
		var handler fasthttp.RequestHandler
		handler = route.Handler

		router.Handle(
			route.Method,
			route.Path,
			logger.Logger(
				middleware.ApplyMiddlewares(
					handler,
					middleware.ContentTypeMiddleware),
				route.Name),
		)
	}

	return router
}

var routes = Routes{
        Route{
		"ThreadCreate",
		strings.ToUpper("Post"),
		"/api/forum/:slug/create",
		controllers.ThreadCreate,
	},
	Route{
		"ForumGetOne",
		strings.ToUpper("Get"),
		"/api/forum/:slug/details",
		controllers.ForumGetOne,
	},

	Route{
		"ForumGetThreads",
		strings.ToUpper("Get"),
		"/api/forum/:slug/threads",
		controllers.ForumGetThreads,
	},

	Route{
		"ForumGetUsers",
		strings.ToUpper("Get"),
		"/api/forum/:slug/users",
		controllers.ForumGetUsers,
	}, ... <here more routes, these are for example>
}

So i have following issue:

panic: wildcard route ':slug' conflicts with existing children in path '/api/forum/:slug/create'

goroutine 1 [running]:
github.com/buaazp/fasthttprouter.(*node).insertChild(0xc0000b62d0, 0xc0000cbc01, 0x6d3d60, 0xc, 0x6d3d55, 0x17, 0xc00009cc00)
	/home/daniknik/go/src/github.com/buaazp/fasthttprouter/tree.go:236 +0x73b
github.com/buaazp/fasthttprouter.(*node).addRoute(0xc0000b62d0, 0x6d3d55, 0x17, 0xc00009cc00)
	/home/daniknik/go/src/github.com/buaazp/fasthttprouter/tree.go:193 +0x20c
github.com/buaazp/fasthttprouter.(*Router).Handle(0xc000084de0, 0xc00008c570, 0x4, 0x6d3d55, 0x17, 0xc00009cc00)
	/home/daniknik/go/src/github.com/buaazp/fasthttprouter/router.go:210 +0xbe
github.com/DanikNik/tech-park-db-hw/internal/pkg/router.NewRouter(0x4070e0)
	/home/daniknik/go/src/github.com/DanikNik/tech-park-db-hw/internal/pkg/router/router.go:27 +0x19f
main.main()
	/home/daniknik/go/src/github.com/DanikNik/tech-park-db-hw/cmd/main.go:10 +0x26

Am I using path variables incorrect or something else?

GET request to POST-endpoint w/ parameters

Maybe related to #15, although this error is not fixed in current master.

The problem

Making a HTTP-GET request to a parameterized HTTP-POST endpoint, that does not have a defined GET endpoint. This panics (because it attempts to set the userdata / token, when no *Context exists (because we're still within the allowed method of fasthttprouter)).

The URL registered would be something like "/test/:my_parameter"

The log

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x707672]

goroutine 22 [running]:
github.com/valyala/fasthttp.(*RequestCtx).SetUserValue(0x0, 0x81c38d, 0x5, 0x78c720, 0xc42018c100)
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/server.go:461 +0x22
github.com/buaazp/fasthttprouter.(*node).getValue(0xc42001c5f0, 0xc42018c0e1, 0xa, 0x0, 0xc42007cf30, 0x0)
	/home/etiennebruines/workspaces/go/src/github.com/buaazp/fasthttprouter/tree.go:364 +0x1ae
github.com/buaazp/fasthttprouter.(*Router).allowed(0xc4200173b0, 0xc42018c0e0, 0xb, 0xc420046bc8, 0x3, 0x0, 0xc)
	/home/etiennebruines/workspaces/go/src/github.com/buaazp/fasthttprouter/router.go:274 +0x318
github.com/buaazp/fasthttprouter.(*Router).Handler(0xc4200173b0, 0xc4200a4d80)
	/home/etiennebruines/workspaces/go/src/github.com/buaazp/fasthttprouter/router.go:354 +0x229
github.com/buaazp/fasthttprouter.(*Router).Handler-fm(0xc4200a4d80)
	/home/etiennebruines/workspaces/go/src/github.com/WebcustomsIT/shopware-bot/bot.go:42 +0x34
github.com/valyala/fasthttp.(*Server).serveConn(0xc4204be280, 0xa2a020, 0xc420118000, 0x1, 0x101)
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/server.go:1554 +0x6e4
github.com/valyala/fasthttp.(*Server).(github.com/valyala/fasthttp.serveConn)-fm(0xa2a020, 0xc420118000, 0x1, 0x0)
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/server.go:1268 +0x3e
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc4202ca980, 0xc42000c480)
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/workerpool.go:210 +0xd2
github.com/valyala/fasthttp.(*workerPool).getCh.func1(0xc4202ca980, 0xc42000c480, 0x77a660, 0xc42000c480)
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/workerpool.go:182 +0x35
created by github.com/valyala/fasthttp.(*workerPool).getCh
	/home/etiennebruines/workspaces/go/src/github.com/valyala/fasthttp/workerpool.go:181 +0x138
exit status 2

Misc

Tested on go1.7.3 and on a master-branch of Go after 1.8 release.

Support more than one path param

The library does not support more than one path parameter being used (e.g. /:path/:path2) for a single route, otherwise it gives a gives a param error during startup.

Noob trying to use this router

I'm getting the "use of package fasthttprouter without selector". Btw, I've only been playing with GoLang for maybe 15 minutes so I'm pretty new to GoLang. Thanks!

main.go

package main

import (
    "fmt"
    "log"
    "os"

    "./routes"

    "github.com/joho/godotenv"
    "github.com/valyala/fasthttp"
)

func loadEnvFile() (bool) {
    err := godotenv.Load()
    if err != nil {
        return true
    }
    return false
}

func setPort() (string) {
    port := os.Getenv("PORT")
    if port == "" {
        port = ":3000"
    } else {
        port = ":" + port
    }
    return port
}

func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(ctx, "Hi there! RequestURI is %q",ctx.RequestURI())
}

func main() {
    if loadEnvFile() {
        fmt.Println("Error loading .env file")
        return
    }

    env := os.Getenv("ENV")
    port := setPort()
    if env == "production" {
        port = ":443"
    }

    fmt.Println("Server listening on port",port)
    log.Fatal(fasthttp.ListenAndServe(port,router.RouterHandler))

}

routes/router.go

package router

import (
    "fmt"

    "github.com/buaazp/fasthttprouter"
    "github.com/valyala/fasthttp"
)

func RouterHandler() (fasthttprouter) {
    router := fasthttprouter.New()
    router.GET("/",func(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
        fmt.Fprint(ctx,"Welcome!\n")
    })
    router.GET("/hello/:name",func(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) {
        fmt.Fprintf(ctx, "hello, %s!\n", ps.ByName("name"))
    })

    return router.Handler
}

CORS

How to handler CORS? Thanks

License-related question

Hi.
I'm working on gramework, and tonight I've integrated modified fasthttprouter. I was unable to solve integration problems without rewriting it to use *gramework.Context instead of *fasthttp.RequestCtx.
So, first of all, any fasthttprouter-related code placed in fasthttprouter_*.go files. Second, I modified fasthttprouter file headers so now it looks like this:

// Copyright 2013 Julien Schmidt. All rights reserved.
// Copyright (c) 2015-2016, 招牌疯子
// Copyright (c) 2017, Kirill Danshin
// Use of this source code is governed by a BSD-style license that can be found
// in the 3rd-Party License/fasthttprouter file.

This header placed in all fasthttprouter_*.go files except fasthttprouter_cache*.go, that I've implemented from scratch.

Licenses placed in this file earlier, because I've forked fasthttprouter 5 days ago to implement hot paths caching.

So, I've changed all uses of fasthttp RequestCtx to gramework Context, slightly optimize router, implemented simple cache for hot paths, and changed all tests so they now passed as expected.

My question is simple: is it ok? Should I change/fix something?

/cc @julienschmidt

Is it willing to support the sub-router?

In a large-scale collaborative project, the sub-router is too much important, such as Django, a full-stack web framework like RoR, which is implemented by Python.

missing stack trace in case of panic

var panicHandler = func(ctx *fasthttp.RequestCtx, p interface{}) {
	// use runtime to get error stack
}
....
....

// intialise router
router = fasthttprouter.New()
router.PanicHandler = panicHandler

If panic has occurred inside my code, then in panicHandler I am not able to see the stack trace where panic started, it shows only fasthttp stack. Anyway to see the original stack ?

Static file example?

Hi, I'm having no luck trying to implement a static file handler for a given request path. I can see your comment in Readme ...use a distinct sub-path for serving files, like /static/*filepath but I cannot make it work. I tried this without success:

router.GET("/js/*filepath", fasthttp.FSHandler("../static/js", 0)) 

Could you please add a working example?

net.Listener (question)

@buaazp how will i implement this in fasthttprouter?

as @valyala stated:
- Use reuseport listener.
- Run a separate server instance per CPU core with GOMAXPROCS=1.

i used something like this in my fasthttp server:
in func main:

s := &fasthttp.Server{
        Handler: mainHandler,
        Name: "hx_server",
    }
    ln := getListener()
    if err = s.Serve(ln); err != nil {
        log.Fatalf("Error when serving incoming connections: %s", err)
    }

and

func getListener() net.Listener {
    if !*prefork {
        runtime.GOMAXPROCS(runtime.NumCPU())
        ln, err := net.Listen("tcp4", *listenAddr)
        if err != nil {
            log.Fatal(err)
            log.Fatal("PREFORK ERROR")
        }
        return ln
    }

    if !*child {
        children := make([]*exec.Cmd, (runtime.NumCPU()-1))
        for i := range children {
            children[i] = exec.Command(os.Args[0], "-prefork", "-child")
            children[i].Stdout = os.Stdout
            children[i].Stderr = os.Stderr
            if err := children[i].Start(); err != nil {
                log.Fatal(err)
            }
        }
        for _, ch := range children {
            if err := ch.Wait(); err != nil {
                log.Print(err)
            }
        }
        os.Exit(0)
        panic("unreachable")
    }

    runtime.GOMAXPROCS(1)
    ln, err := reuseport.Listen("tcp4", *listenAddr)
    if err != nil {
        log.Fatal(err)
        log.Fatal("GETLISTENER ERROR")
    }
    return ln
}

then i run my server as ./server -prefork

question is, how will i implement this using fasthttprouter? i want to have the router and i really want to use this one. is there any way i can achieve this using fasthttprouter?
Thanks in advance.

Router allocates on the heap

Because the router is converting bytes slices to strings it allocates memory on the heap for each request.

This can be prevented by casting the slice to a string. The downside of this approach is that the UserValues will only be valid during the request as after the request they will change when the next request reuses the memory. It also means that changing the UserValue will change the request URI as well. This doesn't seem to be true.

diff --git a/router.go b/router.go
index 57c6e13..4e8fac9 100644
--- a/router.go
+++ b/router.go
@@ -75,6 +75,7 @@ package fasthttprouter
 
 import (
        "strings"
+       "unsafe"
 
        "github.com/valyala/fasthttp"
 )
@@ -293,8 +294,8 @@ func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
                defer r.recv(ctx)
        }
 
-       path := string(ctx.Path())
-       method := string(ctx.Method())
+       path := b2s(ctx.Path())
+       method := b2s(ctx.Method())
        if root := r.trees[method]; root != nil {
                if f, tsr := root.getValue(path, ctx); f != nil {
                        f(ctx)
@@ -372,3 +373,12 @@ func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
                        fasthttp.StatusNotFound)
        }
 }
+
+// b2s converts byte slice to a string without memory allocation.
+// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
+//
+// Note it may break if string and/or slice header will change
+// in the future go versions.
+func b2s(b []byte) string {
+       return *(*string)(unsafe.Pointer(&b))
+}

[bug] Panic on HEAD request to parameterised queries

Run this hello world snippet

package main

import (
	"fmt"
	"log"

	"github.com/buaazp/fasthttprouter"
	"github.com/valyala/fasthttp"
)

func Hello(ctx *fasthttp.RequestCtx) {
	fmt.Fprintf(ctx, "hello, %s!\n", ctx.UserValue("name"))
}

func main() {
	router := fasthttprouter.New()
	router.GET("/hello/:name", Hello)

	log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler))
}

Send a HEAD request

$ curl -I http://localhost:8080/hello/test                                                         47ms 
curl: (52) Empty reply from server

Results in:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x482962]

goroutine 34 [running]:
panic(0x634b40, 0xc42000c100)
	/usr/local/go/src/runtime/panic.go:500 +0x1a1
github.com/valyala/fasthttp.(*RequestCtx).SetUserValue(0x0, 0x67ee99, 0x4, 0x621d40, 0xc4201280d0)
	/home/kailash/code/go/src/github.com/valyala/fasthttp/server.go:461 +0x22
github.com/buaazp/fasthttprouter.(*node).getValue(0xc420018780, 0xc4201280c7, 0x4, 0x0, 0xc4201182f8, 0xfe5)
	/home/kailash/code/go/src/github.com/buaazp/fasthttprouter/tree.go:364 +0x1c7
github.com/buaazp/fasthttprouter.(*Router).allowed(0xc420013200, 0xc4201280c0, 0xb, 0xc42003ac98, 0x4, 0x4, 0x59)
	/home/kailash/code/go/src/github.com/buaazp/fasthttprouter/router.go:273 +0x13d
github.com/buaazp/fasthttprouter.(*Router).Handler(0xc420013200, 0xc420138000)
	/home/kailash/code/go/src/github.com/buaazp/fasthttprouter/router.go:353 +0x23e
github.com/buaazp/fasthttprouter.(*Router).Handler-fm(0xc420138000)
	/home/kailash/Desktop/fast.go:19 +0x34
github.com/valyala/fasthttp.(*Server).serveConn(0xc4200983c0, 0x794040, 0xc420132000, 0x1, 0x101)
	/home/kailash/code/go/src/github.com/valyala/fasthttp/server.go:1536 +0x573
github.com/valyala/fasthttp.(*Server).(github.com/valyala/fasthttp.serveConn)-fm(0x794040, 0xc420132000, 0xc420120758, 0x1)
	/home/kailash/code/go/src/github.com/valyala/fasthttp/server.go:1250 +0x3e
github.com/valyala/fasthttp.(*workerPool).workerFunc(0xc420092480, 0xc42012a100)
	/home/kailash/code/go/src/github.com/valyala/fasthttp/workerpool.go:210 +0xde
github.com/valyala/fasthttp.(*workerPool).getCh.func1(0xc420092480, 0xc42012a100, 0x616480, 0xc42012a100)
	/home/kailash/code/go/src/github.com/valyala/fasthttp/workerpool.go:182 +0x35
created by github.com/valyala/fasthttp.(*workerPool).getCh
	/home/kailash/code/go/src/github.com/valyala/fasthttp/workerpool.go:184 +0x111
exit status 2

random fail response from server

Refer to:
valyala/fasthttp#261

Go 1.8.1
fasthttp version: b154429
fasthttprouter version: ade4e20

Get random fail response when testing:
curl: (52) Empty reply from server
curl: (56) Failure when receiving data from the peer

The problem disappeared when I don't use router. So I guess maybe it's incompatible between fasthttprouter and new fasthttp?

Ask: how to rewrite body?

If I use router.NotFound = fasthttp.FSHandler("./public", 0) to handle the static files, but I want to add a custom page if the static file not found, what should I do?

JWT middleware support

It whould be nice to have an implementation of JWT auth middleware like an existing basic auth.
Thanx!

Recognize defined path in handler

Hi!

Let say I had

GET("/customer/:id", handler)

How can I find the original path "/customer/:id" inside func handler() ?
Thank you

Static files from root

Hello,

is there any way to handle a static file eg /text.txt directly from root? If I use router.ServeFiles (/ * filepath, "./assets") I get a bug with children / * filepath

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.