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