源码走读: fasthttp 为什么这么快?
前戏 今天我们聊聊 golang 的 web 框架, fasthttp 和 gin 到底谁更丝滑? fasthttp 简介 安装 go get -u github.com/valyala/fasthttp fasthttp 性能吊打 net/http 简而言之,fasthttp服务器的速度比net/http快多达 10 倍, 具体参数可以查看官网https://github.com/valyala/fasthttp fasthttp 使用方式与 net/http 有所差异 // using the given handler. func ListenAndServe(addr string, handler RequestHandler) error { s := &Server{ Handler: handler, } return s.ListenAndServe(addr) } type RequestHandler func(ctx *RequestCtx) 可以这样使用: type MyHandler struct { foobar string } // request handler in net/http style, i.e. method bound to MyHandler struct. func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) { // notice that we may access MyHandler properties here - see h.foobar. fmt.Fprintf(ctx, "Hello, world! Requested path is %q. Foobar is %q", ctx.Path(), h.foobar) } // pass bound struct method to fasthttp myHandler := &MyHandler{ foobar: "foobar", } fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP) 在多个handler的时候需要这样使用: ...