// Copyright 2022 Terin Stock. // SPDX-License-Identifier: MPL-2.0 package server import ( "context" "net" "net/http" "strconv" "time" "github.com/gorilla/mux" ) type Server struct { mux *mux.Router host string port int } type Options struct { Host string Port int } func New(options Options) *Server { return &Server{ mux: mux.NewRouter(), host: options.Host, port: options.Port, } } func (s *Server) Register(path string, handler http.Handler) { s.mux.Handle(path, handler) } func (s *Server) Start(ctx context.Context) error { ln, err := net.Listen("tcp", net.JoinHostPort(s.host, strconv.Itoa(s.port))) if err != nil { return err } srv := &http.Server{ Handler: s.mux, MaxHeaderBytes: 1 << 20, IdleTimeout: 90 * time.Second, ReadHeaderTimeout: 32 * time.Second, } shutdownCh := make(chan struct{}) go func() { <-ctx.Done() if err := srv.Shutdown(context.Background()); err != nil { _ = err } close(shutdownCh) }() if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed { return err } <-shutdownCh return nil }