99 lines
2.4 KiB
Go

package server
import (
"context"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"git.akyoto.dev/go/router"
)
// Server represents a single web service.
type Server struct {
Router *router.Router[Handler]
Config Configuration
}
// New creates a new server.
func New() *Server {
return &Server{
Router: router.New[Handler](),
Config: defaultConfig(),
}
}
// Get registers your function to be called when the given GET path has been requested.
func (server *Server) Get(path string, handler Handler) {
server.Router.Add(http.MethodGet, path, handler)
}
// Post registers your function to be called when the given POST path has been requested.
func (server *Server) Post(path string, handler Handler) {
server.Router.Add(http.MethodPost, path, handler)
}
// Delete registers your function to be called when the given DELETE path has been requested.
func (server *Server) Delete(path string, handler Handler) {
server.Router.Add(http.MethodDelete, path, handler)
}
// Put registers your function to be called when the given PUT path has been requested.
func (server *Server) Put(path string, handler Handler) {
server.Router.Add(http.MethodPut, path, handler)
}
// ServeHTTP responds to the given request.
func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
ctx := newContext(request, response)
defer contextPool.Put(ctx)
handler := server.Router.LookupNoAlloc(request.Method, request.URL.Path, ctx.addParameter)
if handler == nil {
response.WriteHeader(http.StatusNotFound)
response.(io.StringWriter).WriteString(http.StatusText(http.StatusNotFound))
return
}
err := handler(ctx)
if err != nil {
response.(io.StringWriter).WriteString(err.Error())
log.Println(request.URL, err)
}
}
// Run starts the server on the given address.
func (server *Server) Run(address string) error {
srv := &http.Server{
Addr: address,
Handler: server,
ReadTimeout: server.Config.Timeout.Read,
WriteTimeout: server.Config.Timeout.Write,
IdleTimeout: server.Config.Timeout.Idle,
ReadHeaderTimeout: server.Config.Timeout.ReadHeader,
}
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
go srv.Serve(listener)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), server.Config.Timeout.Shutdown)
defer cancel()
return srv.Shutdown(ctx)
}