github.com/go-srvc/mods/httpmod
go get github.com/go-srvc/mods/httpmod@v0.2.3
README
httpmod
package main
import (
"errors"
"fmt"
"net/http"
"os"
"github.com/go-srvc/mods/httpmod"
"github.com/go-srvc/srvc"
)
func main() {
srvc.RunAndExit(
httpmod.New(
httpmod.WithServerFn(CreateServer),
),
)
}
func CreateServer() (*http.Server, error) {
addr := os.Getenv("ADDR")
if addr == "" {
return nil, errors.New("ADDR is required")
}
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "World!")
})
return &http.Server{
Addr: addr,
Handler: mux,
}, nil
}
Overview
Package httpmod provides http server as module.
Constants
const ID = "httpmod"Types
type Opt
type Opt func(s *Server) errortype Server
type Server struct {
// contains filtered or unexported fields
}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")
})),
),
)
}