Documentation ¶
Overview ¶
Package runhttp provides functions for running an HTTP server.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Serve ¶
Serve runs the given HTTP server until the context is Done.
Example ¶
package main import ( "context" "fmt" "log" "net" "net/http" "os" "os/signal" "zombiezen.com/go/bass/runhttp" ) func main() { // Set up the context to be canceled when receiving SIGINT. ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() // Set up http.Server. portString := os.Getenv("PORT") if portString == "" { portString = "8080" } srv := &http.Server{ Addr: ":" + portString, } // Run the http.Server. err := runhttp.Serve(ctx, srv, &runhttp.Options{ OnStartup: func(ctx context.Context, addr net.Addr) { s := addr.String() if tcpAddr, ok := addr.(*net.TCPAddr); ok { s = fmt.Sprintf("localhost:%d", tcpAddr.Port) } log.Printf("Listening on http://%s", s) }, OnShutdown: func(ctx context.Context) { log.Printf("Shutting down...") }, OnShutdownError: func(ctx context.Context, err error) { log.Printf("During shutdown: %v", err) }, }) if err != nil { log.Println(err) os.Exit(1) } }
Output:
Types ¶
type Options ¶
type Options struct { // Listener will be used if non-nil to serve on. // Otherwise, the [*http.Server.Addr] will be used to listen for TCP connections. Listener net.Listener // OnStartup will be called after the listener is ready, // but before serving starts. OnStartup func(context.Context, net.Addr) // OnShutdown will be called after the Context is Done, // but before [*http.Server.Shutdown] starts. OnShutdown func(context.Context) // OnShutdownError will be called if [*http.Server.Shutdown] returns a non-nil error. OnShutdownError func(context.Context, error) }
Options holds the optional arguments to Serve.
Click to show internal directories.
Click to hide internal directories.