diff options
author | 2022-11-26 19:59:15 +0100 | |
---|---|---|
committer | 2022-11-26 23:51:25 +0100 | |
commit | f4ce6ac1be7b2817a8e02fc0e517d93ff9890d2e (patch) | |
tree | 9474949eb2a2f21e5276a72bd3acdb499c37b5a5 /server/server.go | |
parent | initial commit (diff) | |
download | cgit-httpd-f4ce6ac1be7b2817a8e02fc0e517d93ff9890d2e.tar.xz |
add initial version of cgit-httpd
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 +} |