about summary refs log tree commit diff stats
path: root/internal/server/server.go
blob: 31db3478fa1a714c4372683f583620ee0e8d889a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package server

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"slices"
	"time"

	cfg "website/internal/config"
	"website/internal/log"
	"website/internal/website"

	"github.com/pkg/errors"
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
)

var (
	CommitSHA    = "local"
	ShortSHA     = "local"
	serverHeader = fmt.Sprintf("website (%s)", ShortSHA)
)

type Config struct {
	Production    bool   `conf:"default:false"`
	InDevServer   bool   `conf:"default:false"`
	Root          string `conf:"default:website"`
	ListenAddress string `conf:"default:localhost"`
	Port          string `conf:"default:3000,short:p"`
}

type Server struct {
	*http.Server
}

func applyDevModeOverrides(config *cfg.Config, listenAddress string) {
	config.CSP.ScriptSrc = slices.Insert(config.CSP.ScriptSrc, 0, "'unsafe-inline'")
	config.CSP.ConnectSrc = slices.Insert(config.CSP.ConnectSrc, 0, "'self'")
	config.BaseURL = cfg.URL{
		URL: &url.URL{
			Scheme: "http",
			Host:   listenAddress,
		},
	}
}

func serverHeaderHandler(wrappedHandler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.ProtoMajor >= 2 && r.Header.Get("Host") != "" {
			// net/http does this for HTTP/1.1, but not h2c
			// TODO: check with HTTP/2.0 (i.e. with TLS)
			r.Host = r.Header.Get("Host")
			r.Header.Del("Host")
		}
		w.Header().Set("Server", serverHeader)
		wrappedHandler.ServeHTTP(w, r)
	})
}

func New(runtimeConfig *Config) (*Server, error) {
	var err error
	config, err := cfg.GetConfig()
	if err != nil {
		return nil, errors.WithMessage(err, "error parsing configuration file")
	}

	listenAddress := net.JoinHostPort(runtimeConfig.ListenAddress, runtimeConfig.Port)

	if !runtimeConfig.Production {
		applyDevModeOverrides(config, listenAddress)
	}

	top := http.NewServeMux()
	mux, err := website.NewMux(config, runtimeConfig.Root)
	if err != nil {
		return nil, errors.Wrap(err, "could not create website mux")
	}
	log.Debug("binding main handler to", "host", listenAddress)
	hostname := config.BaseURL.Hostname()

	top.Handle(hostname+"/", mux)

	top.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		newURL := config.BaseURL.JoinPath(r.URL.String())
		http.Redirect(w, r, newURL.String(), 301)
	})

	top.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})

	return &Server{
		&http.Server{
			Addr:              listenAddress,
			ReadHeaderTimeout: 1 * time.Minute,
			Handler: http.MaxBytesHandler(h2c.NewHandler(
				serverHeaderHandler(
					wrapHandlerWithLogging(top),
				),
				&http2.Server{
					IdleTimeout: 15 * time.Minute,
				},
			), 0),
		},
	}, nil
}

func (s *Server) Start() error {
	if err := s.ListenAndServe(); err != http.ErrServerClosed {
		return errors.Wrap(err, "error creating/closing server")
	}

	return nil
}

func (s *Server) Stop() chan struct{} {
	log.Debug("stop called")

	idleConnsClosed := make(chan struct{})

	go func() {
		log.Debug("shutting down server")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		err := s.Server.Shutdown(ctx)
		log.Debug("server shut down")
		if err != nil {
			// Error from closing listeners, or context timeout:
			log.Warn("HTTP server Shutdown", "error", err)
		}
		close(idleConnsClosed)
	}()

	return idleConnsClosed
}