valyala / fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
MIT License
21.66k stars 1.75k forks source link

fasthttp and net/http can coexist #1593

Closed zxpdmw closed 1 year ago

zxpdmw commented 1 year ago

I want to use fasthttp to develop an interface, and net/http to develop a port, and then let the two interfaces monitor the same port.


import (
    "fmt"
    "github.com/buaazp/fasthttprouter"
    "github.com/valyala/fasthttp"
    "log"
    "net/http"
)

func syncInvoke(ctx *fasthttp.RequestCtx) {
    ctx.Response.SetBody([]byte("123"))
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello!")
}

func main() {
    router := fasthttprouter.New()
    router.GET("/123", syncInvoke)
    go func() {
        err := fasthttp.ListenAndServe(":8080", router.Handler)
        if err != nil {
            log.Println(err)
        } else {
            log.Println("fasthttp server success")
        }
    }()
    http.HandleFunc("/test", hello)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Println(err)
    } else {
        log.Printf("http server success")
    }
}

It seems that the following nethttp listenserve cannot be reached is there a solution

erikdubbelboer commented 1 year ago

You can use net/http to listen on the port and then use https://pkg.go.dev/github.com/valyala/fasthttp@v1.48.0/fasthttpadaptor to call the fasthttp handler for the paths that need it.