Baike.dev
All toolsTrendingOpen sourceNewsSubmit
Log in
< 返回工具列表
F

fasthttp

> 编程语言
开源

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

23.4K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp

Fast HTTP implementation for Go.

fasthttp might not be for you!

fasthttp was designed for some high performance edge cases. Unless your server/client needs to handle thousands of small to medium requests per second and needs a consistent low millisecond response time fasthttp might not be for you. For most cases net/http is much better as it's easier to use and can handle more cases. For most cases you won't even notice the performance difference.

General info and links

Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than 1.5M concurrent keep-alive connections per physical server.

TechEmpower Benchmark round 23 results

Server Benchmarks

Client Benchmarks

Install

Documentation

Examples from docs

Code examples

Awesome fasthttp tools

Switching from net/http to fasthttp

Fasthttp best practices

Related projects

FAQ

HTTP server performance comparison with net/http

In short, fasthttp server is up to 6 times faster than net/http. Below are benchmark results.

GOMAXPROCS=1

net/http server:

…

fasthttp server:

…

GOMAXPROCS=4

net/http server:

…

fasthttp server:

…

HTTP client comparison with net/http

In short, fasthttp client is up to 4 times faster than net/http. Below are benchmark results.

GOMAXPROCS=1

net/http client:

…

fasthttp client:

…

GOMAXPROCS=4

net/http client:

…

fasthttp client:

…

Install

go get -u github.com/valyala/fasthttp

Switching from net/http to fasthttp

Unfortunately, fasthttp doesn't provide API identical to net/http. See the FAQ for details. There is net/http -> fasthttp handler converter, but it is better to write fasthttp request handlers by hand in order to use all of the fasthttp advantages (especially high performance :) ).

Important points:

  • Fasthttp works with RequestHandler functions instead of objects implementing Handler interface. Fortunately, it is easy to pass bound struct methods to fasthttp:
…
  • The RequestHandler accepts only one argument - RequestCtx. It contains all the functionality required for http request processing and response writing. Below is an example of a simple request handler conversion from net/http to fasthttp.

    // net/http request handler
    requestHandler := func(w http.ResponseWriter, r *http.Request) {
        switch r.URL.Path {
        case "/foo":
            fooHandler(w, r)
        case "/bar":
            barHandler(w, r)
        default:
            http.Error(w, "Unsupported path", http.StatusNotFound)
        }
    }
    
    // the corresponding fasthttp request handler
    requestHandler := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/foo":
            fooHandler(ctx)
        case "/bar":
            barHandler(ctx)
        default:
            ctx.Error("Unsupported path", fasthttp.StatusNotFound)
        }
    }
    
  • Fasthttp allows setting response headers and writing response body in an arbitrary order. There is no 'headers first, then body' restriction like in net/http. The following code is valid for fasthttp:

…
  • Fasthttp doesn't provide ServeMux, but there are more powerful third-party routers and web frameworks with fasthttp support:

    • fasthttp-routing
    • router
    • lu
    • atreugo
    • Fiber
    • Gearbox

    Net/http code with simple ServeMux is trivially converted to fasthttp code:

    // net/http code
    
    m := &http.ServeMux{}
    m.HandleFunc("/foo", fooHandlerFunc)
    m.HandleFunc("/bar", barHandlerFunc)
    m.Handle("/baz", bazHandler)
    
    http.ListenAndServe(":80", m)
    
    // the corresponding fasthttp code
    m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/foo":
            fooHandlerFunc(ctx)
        case "/bar":
            barHandlerFunc(ctx)
        case "/baz":
            bazHandler.HandlerFunc(ctx)
        default:
            ctx.Error("not found", fasthttp.StatusNotFound)
        }
    }
    
    fasthttp.ListenAndServe(":80", m)
    
  • Because creating a new channel for every request is just too expensive, so the channel returned by RequestCtx.Done() is only closed when the server is shutting down.

    func main() {
    fasthttp.ListenAndServe(":8080", fasthttp.TimeoutHandler(func(ctx *fasthttp.RequestCtx) {
        select {
        case <-ctx.Done():
            // ctx.Done() is only closed when the server is shutting down.
            log.Println("context cancelled")
            return
        case <-time.After(10 * time.Second):
            log.Println("process finished ok")
        }
    }, time.Second*2, "timeout"))
    }
    
  • net/http -> fasthttp conversion table:

    • All the pseudocode below assumes w, r and ctx have these types:
    var (
        w http.ResponseWriter
        r *http.Request
        ctx *fasthttp.RequestCtx
    )
    
    • r.Body ➜ ctx.PostBody()
    • r.URL.Path ➜ ctx.Path()
    • r.URL ➜ ctx.URI()
    • r.Method ➜ ctx.Method()
    • r.Header ➜ ctx.Request.Header
    • r.Header.Get() ➜ ctx.Request.Header.Peek()
    • r.Host ➜ ctx.Host()
    • r.Form ➜ ctx.QueryArgs() + ctx.PostArgs()
    • r.PostForm ➜ ctx.PostArgs()
    • r.FormValue() ➜ ctx.FormValue()
    • r.FormFile() ➜ ctx.FormFile()
    • r.MultipartForm ➜ ctx.MultipartForm() For untrusted multipart input, use ctx.MultipartFormWithLimit() (or a custom Server.FormValueFunc) to enforce a parsing size limit.
    • r.RemoteAddr ➜ ctx.RemoteAddr()
    • r.RequestURI ➜ ctx.RequestURI()
    • r.TLS ➜ ctx.IsTLS()
    • r.Cookie() ➜ ctx.Request.Header.Cookie()
    • r.Referer() ➜ ctx.Referer()
    • r.UserAgent() ➜ ctx.UserAgent()
    • w.Header() ➜ ctx.Response.Header
    • w.Header().Set() ➜ ctx.Response.Header.Set()
    • w.Header().Set("Content-Type") ➜ ctx.SetContentType()
    • w.Header().Set("Set-Cookie") ➜ ctx.Response.Header.SetCookie()
    • w.Write() ➜ ctx.Write(), ctx.SetBody(), ctx.SetBodyStream(), ctx.SetBodyStreamWriter()
    • w.WriteHeader() ➜ ctx.SetStatusCode()
    • w.(http.Hijacker).Hijack() ➜ ctx.Hijack()
    • http.Error() ➜ ctx.Error()
    • http.FileServer() ➜ fasthttp.FSHandler(), fasthttp.FS
    • http.ServeFile() ➜ fasthttp.ServeFile()
    • http.Redirect() ➜ ctx.Redirect()
    • http.NotFound() ➜ ctx.NotFound()
    • http.StripPrefix() ➜ fasthttp.PathRewriteFunc
  • VERY IMPORTANT! Fasthttp disallows holding references to RequestCtx or to its' members after returning from RequestHandler. Otherwise data races are inevitable. Carefully inspect all the net/http request handlers converted to fasthttp whether they retain references to RequestCtx or to its' members after returning. RequestCtx provides the following band aids for this case:

    • Wrap RequestHandler into [TimeoutHandler](https://pkg.go.dev/github.com/val

核心特点

  • •Fasthttp works with RequestHandler functions
  • •The RequestHandler
  • •Fasthttp allows setting response headers and writing response body
  • •Fasthttp doesn't provide ServeMux,
  • •fasthttp-routing
  • •Because creating a new channel for every request is just too expensive, so the channel returned by RequestCtx.Done() is only closed when the server is shutting down.
  • •net/http -> fasthttp conversion table:
  • •All the pseudocode below assumes w, r and ctx have these types:
  • •r.Body ➜ ctx.PostBody()
  • •r.URL.Path ➜ ctx.Path()

> 标签

Go

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月9日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言
Baike.dev

baike.dev helps you discover great languages, frameworks, databases, DevOps and cloud-native tools.

Quick links

  • Home
  • All tools
  • Trending
  • Open source

About

  • About us
  • Community
  • News

Contribute

Found a great developer tool? Share it with the community.

Submit a tool
© 2026 baike.dev Developer EncyclopediaUpdated daily · Discover great developer tools