package server import ( "context" "fmt" "net" "net/http" "os" "slices" "time" cfg "website/internal/config" "website/internal/log" "website/internal/website" "github.com/getsentry/sentry-go" sentryhttp "github.com/getsentry/sentry-go/http" "github.com/pkg/errors" ) var config *cfg.Config var ( CommitSHA string = "local" ShortSHA string = "local" serverHeader string = 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"` BaseURL cfg.URL `conf:"default:http://localhost:3000,short:b"` } type Server struct { *http.Server } func applyDevModeOverrides(config *cfg.Config) { config.CSP.ScriptSrc = slices.Insert(config.CSP.ScriptSrc, 0, "'unsafe-inline'") config.CSP.ConnectSrc = slices.Insert(config.CSP.ConnectSrc, 0, "'self'") } func serverHeaderHandler(wrappedHandler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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") } if runtimeConfig.InDevServer { applyDevModeOverrides(config) } env := "development" if runtimeConfig.Production { env = "production" } err = sentry.Init(sentry.ClientOptions{ EnableTracing: true, TracesSampleRate: 1.0, Dsn: os.Getenv("SENTRY_DSN"), Release: CommitSHA, Environment: env, }) if err != nil { return nil, errors.WithMessage(err, "could not set up sentry") } defer sentry.Flush(2 * time.Second) sentryHandler := sentryhttp.New(sentryhttp.Options{ Repanic: true, }) top := http.NewServeMux() mux, err := website.NewMux(config, runtimeConfig.Root) if err != nil { return nil, err } log.Debug("binding main handler to", "host", runtimeConfig.BaseURL.Hostname()+"/") hostname := runtimeConfig.BaseURL.Hostname() top.Handle(hostname+"/", mux) top.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { newURL := runtimeConfig.BaseURL.JoinPath(r.URL.String()) http.Redirect(w, r, newURL.String(), 301) }) top.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) listenAddress := net.JoinHostPort(runtimeConfig.ListenAddress, runtimeConfig.Port) return &Server{ &http.Server{ Addr: listenAddress, Handler: sentryHandler.Handle( serverHeaderHandler( wrapHandlerWithLogging(top, wrappedHandlerOptions{ defaultHostname: runtimeConfig.BaseURL.Hostname(), }), ), ), }, }, nil } func (s *Server) Start() error { if err := s.ListenAndServe(); err != http.ErrServerClosed { return err } 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 }