To run a Netpoll server, follow these steps:
- Create a Listener: You can use either a standard
net.Listener or a netpoll.Listener via netpoll.CreateListener(network, address). - Create an EventLoop: Initialize an
EventLoop using netpoll.NewEventLoop. You must provide an OnRequest handler for business logic. You can also pass configuration options like netpoll.WithOnPrepare or netpoll.WithReadTimeout. - Run the Server: Call
eventLoop.Serve(listener). This is a blocking call that runs until a panic occurs or Shutdown is called. - Shutdown Gracefully: Use
eventLoop.Shutdown(ctx) with a context to stop the server gracefully.
package main
import (
"context"
"time"
"github.com/cloudwego/netpoll"
)
func main() {
// 1. Create Listener
listener, _ := netpoll.CreateListener("tcp", ":8080")
// 2. Create EventLoop
handler := func(ctx context.Context, conn netpoll.Connection) error {
return nil
}
eventLoop, _ := netpoll.NewEventLoop(
handler,
netpoll.WithReadTimeout(time.Second),
)
// 3. Run Server (blocking)
go func() {
eventLoop.Serve(listener)
}()
// 4. Shutdown
time.Sleep(time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
eventLoop.Shutdown(ctx)
}