aboutsummaryrefslogtreecommitdiff
path: root/server/server.go
diff options
context:
space:
mode:
authorLibravatar Terin Stock <terinjokes@gmail.com>2022-11-26 19:59:15 +0100
committerLibravatar Terin Stock <terinjokes@gmail.com>2022-11-26 23:51:25 +0100
commitf4ce6ac1be7b2817a8e02fc0e517d93ff9890d2e (patch)
tree9474949eb2a2f21e5276a72bd3acdb499c37b5a5 /server/server.go
parentinitial commit (diff)
downloadcgit-httpd-f4ce6ac1be7b2817a8e02fc0e517d93ff9890d2e.tar.xz
add initial version of cgit-httpd
Diffstat (limited to 'server/server.go')
-rw-r--r--server/server.go67
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
+}