diff options
Diffstat (limited to 'server/server.go')
-rw-r--r-- | server/server.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..424f359 --- /dev/null +++ b/server/server.go @@ -0,0 +1,67 @@ +// 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 +} |