//go:build !tinygo && linux package main import ( "log/slog" "os" "strconv" "sync/atomic" "time" "github.com/soypat/lneto/http/httphi" "github.com/soypat/lneto/x/rawsock" ) const ( kB = 1 << 10 listenPort = 8080 bufferSizes = 2 * kB // A browser sends around twenty header fields; a request carrying more // than this is answered 431 rather than parsed into memory it was not // given. Each field costs 8 bytes of table. numHeaderFields = 32 numGoroutines = 4 readTimeout = 2 * time.Second ) func main() { if err := run(); err != nil { println("Error:", err.Error()) os.Exit(1) } println("DONE") } func run() error { var ln rawsock.Listener err := ln.Listen(listenPort) if err != nil { return err } defer ln.Close() print("listening on http://localhost:", listenPort, "\n") var mux httphi.MuxSlice mux.Handle("GET /", homepage) var router httphi.Router err = router.Configure(httphi.RouterConfig{ FixedNumGoroutines: numGoroutines, RequestHeaderBufferSize: bufferSizes, RequestNumHeaderKVCap: numHeaderFields, ResponseHeaderMinBufferSize: bufferSizes, MaxAwaitingConns: 256, Mux: &mux, Logger: slog.Default(), }) if err != nil { return err } defer router.TeardownGoroutines() for { conn := new(rawsock.Conn) err := ln.AcceptConn(conn) if err != nil { return err } // The connection owns the idle policy: a peer that opens a socket and // then stalls fails its read instead of holding a router goroutine. conn.SetReadTimeout(readTimeout) err = router.Handle(conn) if err != nil { // Every goroutine is busy and the queue is full. Dropping the // connection is the backpressure: memory stays bounded. slog.Warn("dropped connection", slog.String("remote", conn.RemoteAddr().String()), slog.String("err", err.Error())) conn.Close() } } } const ( htmlHead = `