Go语言快速HTTP工具——fasthttp探索

发表时间: 2024-05-21 11:21

Go 的快速 HTTP 包。为高性能而调整。热路径中的零内存分配。比 net/http 快 10 倍

https://github.com/valyala/fasthttp

package mainimport (    "flag"    "fmt"    "log"    "github.com/valyala/fasthttp")var (    addr = flag.String("addr", ":8080", "TCP address to listen to")    compress = flag.Bool("compress", false, "Whether to enable transparent response compression"))func main() {    flag.Parse()    h := requestHandler    if *compress {        h = fasthttp.CompressHandler(h)    }    if err := fasthttp.ListenAndServe(*addr, h); err != nil {        log.Fatalf("Error in ListenAndServe: %v", err)    }}func requestHandler(ctx *fasthttp.RequestCtx) {    fmt.Fprintf(ctx, "Hello, world!\n\n")    fmt.Fprintf(ctx, "Request method is %q\n", ctx.Method())    fmt.Fprintf(ctx, "RequestURI is %q\n", ctx.RequestURI())    fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())    fmt.Fprintf(ctx, "Host is %q\n", ctx.Host())    fmt.Fprintf(ctx, "Query string is %q\n", ctx.QueryArgs())    fmt.Fprintf(ctx, "User-Agent is %q\n", ctx.UserAgent())    fmt.Fprintf(ctx, "Connection has been established at %s\n", ctx.ConnTime())    fmt.Fprintf(ctx, "Request has been started at %s\n", ctx.Time())    fmt.Fprintf(ctx, "Serial request number for the current connection is %d\n", ctx.ConnRequestNum())    fmt.Fprintf(ctx, "Your ip is %q\n\n", ctx.RemoteIP())    fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request)    ctx.SetContentType("text/plain; charset=utf8")    // Set arbitrary headers    ctx.Response.Header.Set("X-My-Header", "my-header-value")    // Set cookies    var c fasthttp.Cookie    c.SetKey("cookie-name")    c.SetValue("cookie-value")    ctx.Response.Header.SetCookie(&c)}
> # go run http.go> # curl http://localhost:8080

net/http包

package mainimport (    "log"    "net/http"    "runtime"    "time")func main() {    go func() {        for {        log.Println("当前routine数量:", runtime.NumGoroutine())        time.Sleep(time.Second)        }    }()    http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {    		w.Write([]byte("Hello, Go!"))    }))    log.Fatal(http.ListenAndServe(":8080", nil))}

fasthttp包

package mainimport ("fmt""log"// "net/http""runtime""time""github.com/valyala/fasthttp")func fastHTTPHandler(ctx *fasthttp.RequestCtx) {    fmt.Fprintln(ctx, "Hello, Go!")}func main() {    go func() {        // http.ListenAndServe(":6060", nil)        fasthttp.ListenAndServe(":6060", nil)    }()    go func() {        for {        log.Println("当前routine数量:", runtime.NumGoroutine())        time.Sleep(time.Second)        }    }()    s := &fasthttp.Server{        Handler: fastHTTPHandler,    }    s.ListenAndServe(":8081")}