lesismal / nbio

Pure Go 1000k+ connections solution, support tls/http1.x/websocket and basically compatible with net/http, with high-performance and low memory cost, non-blocking, event-driven, easy-to-use.
MIT License
2.17k stars 153 forks source link

how to use with so reuseport option for the http example? #406

Closed ouvaa closed 6 months ago

ouvaa commented 6 months ago

as titled

lesismal commented 6 months ago

You can set Listen func and NListener like this:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/lesismal/nbio/nbhttp"
    reuseport "github.com/libp2p/go-reuseport"
)

func onEcho(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(time.Now().Format("20060102 15:04:05")))
}

func main() {
    mux := &http.ServeMux{}
    mux.HandleFunc("/", onEcho)

    engine := nbhttp.NewServer(nbhttp.Config{
        Network: "tcp",
        Addrs:   []string{"localhost:8080"},
        Listen:  reuseport.Listen, // set reuseport listen
        // NListener: 2, // how many goroutine to handle Accept for each addr, if not set, 1 goroutine by default
        Handler: mux,
    })

    err := engine.Start()
    if err != nil {
        fmt.Printf("nbio.Start failed: %v\n", err)
        return
    }
    defer engine.Stop()

    <-make(chan int)
}
ouvaa commented 6 months ago

amazing! thx. u should put somewhere easier to find :D i cant believe i'm the first to ask this question

lesismal commented 6 months ago

Some other users asked about reuseport before, but in Chinese: https://github.com/lesismal/nbio/issues/285#issuecomment-1512696017 https://github.com/lesismal/nbio/issues/157#issuecomment-1047563475

I'll do some investment to provide more docs/faq, thx for your feedback bro!