package server import ( "context" "fmt" "net" "net/http" "net/url" "os" "slices" "strconv" "strings" "time" "website/internal/builder" cfg "website/internal/config" "website/internal/log" "website/internal/vcs" "website/internal/website" "github.com/ardanlabs/conf/v3" "github.com/osdevisnot/sorvor/pkg/livereload" "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 { Root string `conf:"default:website"` Redirect bool `conf:"default:true"` ListenAddress string `conf:"default:localhost"` Port int `conf:"default:8080,short:p"` TLSPort int `conf:"default:8443"` TLS bool `conf:"default:false"` Development bool `conf:"default:false,flag:dev"` ACMECA string `conf:"env:ACME_CA"` ACMECACert string `conf:"env:ACME_CA_CERT"` Domains string } type Server struct { *http.Server redirectHandler func(http.ResponseWriter, *http.Request) runtimeConfig *Config config *cfg.Config } func applyDevModeOverrides(config *cfg.Config, runtimeConfig *Config) { config.CSP.ScriptSrc = slices.Insert(config.CSP.ScriptSrc, 0, "'unsafe-inline'") config.CSP.ConnectSrc = slices.Insert(config.CSP.ConnectSrc, 0, "'self'") if runtimeConfig.Domains != "" { config.Domains = strings.Split(runtimeConfig.Domains, ",") } else { config.Domains = []string{runtimeConfig.ListenAddress} } scheme := "http" port := runtimeConfig.Port if runtimeConfig.TLS { scheme = "https" port = runtimeConfig.TLSPort } config.BaseURL = cfg.URL{ URL: &url.URL{ Scheme: scheme, Host: net.JoinHostPort(config.Domains[0], strconv.Itoa(port)), }, } } func updateCSPHashes(config *cfg.Config, r *builder.Result) { clear(config.CSP.StyleSrc) for i, h := range r.Hashes { config.CSP.StyleSrc[i] = fmt.Sprintf("'%s'", h) } } func serverHeaderHandler(wrappedHandler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Debug( "headers", "proto", r.Header.Get("X-Forwarded-Proto"), "host", r.Header.Get("X-Forwarded-Host"), "scheme", r.URL.Scheme, "secure", r.TLS != nil, ) log.Debug("host", "request", r.Host, "header", r.Header.Get("Host")) 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) log.Debug("host", "request", r.Host, "header", r.Header.Get("Host")) r.Host = r.Header.Get("Host") r.Header.Del("Host") } w.Header().Set("Server", serverHeader) wrappedHandler.ServeHTTP(w, r) }) } func rebuild(builderConfig builder.IOConfig, config *cfg.Config) error { r, err := builder.BuildSite(builderConfig, config) if err != nil { return errors.WithMessage(err, "could not build site") } updateCSPHashes(config, r) return nil } func New(runtimeConfig *Config) (*Server, error) { if !runtimeConfig.Development { vcsConfig := &vcs.Config{} _, err := conf.Parse("", vcsConfig) if err != nil { return nil, err } _, err = vcs.CloneOrUpdate(vcsConfig) if err != nil { return nil, err } err = os.Chdir(vcsConfig.LocalPath) if err != nil { return nil, err } runtimeConfig.Root = "website" } config, err := cfg.GetConfig() if err != nil { return nil, errors.WithMessage(err, "error parsing configuration file") } if runtimeConfig.Development { applyDevModeOverrides(config, runtimeConfig) } listenAddress := net.JoinHostPort(runtimeConfig.ListenAddress, strconv.Itoa(runtimeConfig.Port)) top := http.NewServeMux() builderConfig := builder.IOConfig{ Source: "content", Destination: runtimeConfig.Root, Development: runtimeConfig.Development, } err = rebuild(builderConfig, config) if err != nil { return nil, err } if runtimeConfig.Development { liveReload := livereload.New() top.Handle("/_/reload", liveReload) liveReload.Start() fw, err := NewFileWatcher() if err != nil { return nil, errors.WithMessage(err, "could not create file watcher") } for _, dir := range []string{"content", "static", "templates", "internal/builder"} { err := fw.AddRecursive(dir) if err != nil { return nil, errors.WithMessagef( err, "could not add directory %s to file watcher", dir, ) } } err = fw.Add(".") if err != nil { return nil, errors.WithMessage(err, "could not add directory to file watcher") } go fw.Start(func(filename string) { log.Info("rebuilding site", "changed_file", filename) err := rebuild(builderConfig, config) if err != nil { log.Error("error rebuilding site", "error", err) } }) } loggingMux := http.NewServeMux() mux, err := website.NewMux(config, runtimeConfig.Root) if err != nil { return nil, errors.Wrap(err, "could not create website mux") } redirectHandler := func(w http.ResponseWriter, r *http.Request) { path, _ := website.CanonicalisePath(r.URL.Path) newURL := config.BaseURL.JoinPath(path) http.Redirect(w, r, newURL.String(), 301) } if runtimeConfig.Redirect { loggingMux.Handle(config.BaseURL.Hostname()+"/", mux) loggingMux.HandleFunc("/", redirectHandler) } else { loggingMux.Handle("/", mux) } top.Handle("/", serverHeaderHandler( wrapHandlerWithLogging(loggingMux), ), ) top.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) return &Server{ Server: &http.Server{ Addr: listenAddress, ReadHeaderTimeout: 1 * time.Minute, Handler: http.MaxBytesHandler(h2c.NewHandler( top, &http2.Server{ IdleTimeout: 15 * time.Minute, }, ), 0), }, redirectHandler: redirectHandler, config: config, runtimeConfig: runtimeConfig, }, nil } func (s *Server) serve(tls bool) error { if tls { return s.serveTLS() } return s.serveTCP() } func (s *Server) Start() error { if err := s.serve(s.runtimeConfig.TLS); 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 }