github.com/go-srvc/mods/httpmod
go get github.com/go-srvc/mods/httpmod@v1.14.0
README
httpmod
httpmod runs an http.Server as a srvc module and shuts it down gracefully on exit.
package main
import (
"fmt"
"net/http"
"os"
"github.com/go-srvc/mods/httpmod"
"github.com/go-srvc/mods/sigmod"
"github.com/go-srvc/srvc"
)
func main() {
srvc.RunAndExit(
sigmod.New(os.Interrupt),
httpmod.New(
httpmod.WithAddr(":8080"),
httpmod.WithHandler(http.HandlerFunc(hello)),
),
)
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello, world")
}
Overview
Package httpmod provides http server as module.
Constants
const ID = "httpmod"Types
type Opt
type Opt func(s *Server) errorfunc WithAddr
func WithAddr(addr string) OptWithAddr sets http.Server.Addr.
func WithAddrFn
func WithAddrFn(fn func() (string, error)) OptWithAddrFn sets http.Server.Addr using value returned from fn.
func WithHandler
func WithHandler(h http.Handler) OptWithHandler sets http.Server.Handler.
func WithHandlerFn
func WithHandlerFn(fn func() (http.Handler, error)) OptWithHandlerFn sets http.Server.Handler using value returned from fn.
func WithServer
func WithServer(srv *http.Server) OptWithServer sets http.Server for module.
func WithServerFn
func WithServerFn(fn func() (*http.Server, error)) OptWithServerFn sets http.Server using value returned from fn.
func WithShutdownTimeout
func WithShutdownTimeout(d time.Duration) OptWithShutdownTimeout sets timeout for graceful shutdown.
type Server
type Server struct {
// contains filtered or unexported fields
}func New
func New(opts ...Opt) *ServerNew creates Server with given options.
func (*Server) ID
func (s *Server) ID() stringfunc (*Server) Init
func (s *Server) Init() errorInit starts net.Listener after applying all options. Options are applied in same order as they were provided.
func (*Server) Run
func (s *Server) Run() errorRun starts serving http request and can be called after initialization.
func (*Server) Stop
func (s *Server) Stop() errorStop calls shutdown for server.
func (*Server) URL
func (s *Server) URL() stringURL returns server's URL and can be called after initialization.
Examples
ExampleNew
package main
import (
"fmt"
"net/http"
"time"
"github.com/go-srvc/mods/httpmod"
"github.com/go-srvc/srvc"
)
func main() {
srvc.RunAndExit(
httpmod.New(
httpmod.WithServer(&http.Server{ReadHeaderTimeout: time.Second}),
httpmod.WithAddr("127.0.0.1:0"),
httpmod.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello")
})),
),
)
}