Package: websrv
Simple, configurable HTTP server with graceful shutdown, operating modes, logging levels, and sensible timeouts.
Repository: https://github.com/dracory/websrv
Install
go get github.com/dracory/websrv@latest
Quick Start
package main
import (
"net/http"
"github.com/dracory/websrv"
)
func main() {
_, _ = websrv.Start(websrv.Options{
Host: "localhost",
Port: "8080",
URL: "http://localhost:8080",
Handler: func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello")) },
Mode: websrv.ProductionMode,
LogLevel: websrv.LogLevelInfo,
})
}
Features
- Configurable host, port, URL, and top-level handler
- Production and Testing modes
- Logging levels: debug, info, error, none (uses
cfmt
) - Graceful shutdown on
SIGINT
/SIGTERM
- Timeouts: read/write/header/idle
Options
type Options struct {
Host string
Port string
URL string // optional, for logs
Handler func(w http.ResponseWriter, r *http.Request)
Mode string // default: ProductionMode
LogLevel LogLevel // default: LogLevelInfo
}
Log levels: LogLevelDebug
, LogLevelInfo
, LogLevelError
, LogLevelNone
Modes: ProductionMode
, TestingMode
Using with a Router
Pass your router's ServeHTTP
as the handler; websrv
mounts it at /
under an internal http.ServeMux
.
serverHandler := myRouter.ServeHTTP
_, _ = websrv.Start(websrv.Options{
Host: "0.0.0.0", Port: "8080", Handler: serverHandler,
})
Testing Pattern
Use TestingMode
to avoid process exit and signal the server to stop in tests.
_, _ = websrv.Start(websrv.Options{
Host: "localhost", Port: "8080",
Handler: func(w http.ResponseWriter, r *http.Request) {},
Mode: websrv.TestingMode,
})
// In tests, wait until server responds, then send SIGTERM to trigger shutdown.
Notes
- In Production mode,
Start
callsos.Exit(0)
after graceful shutdown. - Set
LogLevelNone
for silent runs (e.g., benchmarks/tests).