fasthttp does not provide an API identical to Go's standard net/http. While a fasthttpadaptor exists to convert net/http handlers, it is recommended to write native fasthttp handlers manually to fully leverage the library's performance advantages.
Key Differences
- Handler Type: fasthttp uses
RequestHandler functions instead of the http.Handler interface. You can pass bound struct methods to fasthttp.ListenAndServe to maintain state. - Request Context: The
RequestHandler accepts a single argument, *fasthttp.RequestCtx, which encapsulates all request and response functionality. - Response Ordering: Unlike
net/http, fasthttp allows you to set headers, status codes, and write the body in any order. The response is not sent to the wire until the RequestHandler returns. - Routing: fasthttp does not include a built-in
ServeMux. Instead, developers typically use third-party routers like fasthttp-routing, router, or high-level frameworks like Fiber or atreugo.
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) {
fmt.Fprintf(ctx, "Hello, world! Requested path is %q. Foobar is %q",
ctx.Path(), h.foobar)
}
myHandler := &MyHandler{
foobar: "foobar",
}
fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP)