// Package api is the HTTP server of the core: health checks today, the // Telegram webhook when enabled, and later the worker and Mini App APIs. package api import ( "context" "encoding/json" "errors" "log/slog" "net" "net/http" "time" ) // Server is the core HTTP server. type Server struct { mux *http.ServeMux srv *http.Server log *slog.Logger health func(ctx context.Context) error ln net.Listener } // New creates the server. health reports whether the core can serve; it is // called on every /healthz request. func New(listen string, health func(ctx context.Context) error, log *slog.Logger) *Server { if log == nil { log = slog.Default() } s := &Server{mux: http.NewServeMux(), log: log, health: health} s.srv = &http.Server{ Addr: listen, Handler: s.mux, ReadHeaderTimeout: 10 * time.Second, } s.mux.HandleFunc("GET /healthz", s.handleHealth) return s } // Mux exposes the router so other parts can add their routes. func (s *Server) Mux() *http.ServeMux { return s.mux } func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) defer cancel() status, code := "ok", http.StatusOK if s.health != nil { if err := s.health(ctx); err != nil { s.log.Warn("health check failed", "err", err) status, code = "unavailable", http.StatusServiceUnavailable } } w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(map[string]string{"status": status}) } // Listen binds the address. It is separate from Serve so startup fails // early when the port is taken. func (s *Server) Listen() error { ln, err := net.Listen("tcp", s.srv.Addr) if err != nil { return err } s.ln = ln return nil } // Addr returns the bound address, useful when the port was 0. func (s *Server) Addr() string { if s.ln == nil { return s.srv.Addr } return s.ln.Addr().String() } // Serve runs until ctx ends, then shuts down gracefully. func (s *Server) Serve(ctx context.Context) error { if s.ln == nil { if err := s.Listen(); err != nil { return err } } errc := make(chan error, 1) go func() { errc <- s.srv.Serve(s.ln) }() select { case err := <-errc: if errors.Is(err, http.ErrServerClosed) { return nil } return err case <-ctx.Done(): shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() return s.srv.Shutdown(shutCtx) } }