http.go

 1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6	"time"
 7
 8	"github.com/charmbracelet/log"
 9	"github.com/charmbracelet/soft-serve/pkg/config"
10)
11
12// HTTPServer is an http server.
13type HTTPServer struct {
14	ctx    context.Context
15	cfg    *config.Config
16	server *http.Server
17}
18
19// NewHTTPServer creates a new HTTP server.
20func NewHTTPServer(ctx context.Context) (*HTTPServer, error) {
21	cfg := config.FromContext(ctx)
22	logger := log.FromContext(ctx)
23	s := &HTTPServer{
24		ctx: ctx,
25		cfg: cfg,
26		server: &http.Server{
27			Addr:              cfg.HTTP.ListenAddr,
28			Handler:           NewRouter(ctx),
29			ReadHeaderTimeout: time.Second * 10,
30			IdleTimeout:       time.Second * 10,
31			MaxHeaderBytes:    http.DefaultMaxHeaderBytes,
32			ErrorLog:          logger.StandardLog(log.StandardLogOptions{ForceLevel: log.ErrorLevel}),
33		},
34	}
35
36	return s, nil
37}
38
39// Close closes the HTTP server.
40func (s *HTTPServer) Close() error {
41	return s.server.Close()
42}
43
44// ListenAndServe starts the HTTP server.
45func (s *HTTPServer) ListenAndServe() error {
46	if s.cfg.HTTP.TLSKeyPath != "" && s.cfg.HTTP.TLSCertPath != "" {
47		return s.server.ListenAndServeTLS(s.cfg.HTTP.TLSCertPath, s.cfg.HTTP.TLSKeyPath)
48	}
49	return s.server.ListenAndServe()
50}
51
52// Shutdown gracefully shuts down the HTTP server.
53func (s *HTTPServer) Shutdown(ctx context.Context) error {
54	return s.server.Shutdown(ctx)
55}