76 lines
1.6 KiB
Go
76 lines
1.6 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/charmbracelet/log"
|
|
)
|
|
|
|
type WebServer struct {
|
|
server *Server
|
|
logger *log.Logger
|
|
httpServer *http.Server
|
|
}
|
|
|
|
func NewWebServer(server *Server) *WebServer {
|
|
ws := &WebServer{
|
|
server: server,
|
|
logger: server.Logger,
|
|
httpServer: &http.Server{
|
|
Addr: fmt.Sprintf(":%d", server.Config.Web.Port),
|
|
},
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/health", ws.healthHandler)
|
|
mux.HandleFunc("/next_birthdays", ws.nextBirthdayHandler)
|
|
|
|
ws.httpServer.Handler = mux
|
|
|
|
return ws
|
|
}
|
|
|
|
func (ws *WebServer) Start() error {
|
|
ws.logger.Debug("starting web server")
|
|
|
|
go func() {
|
|
if err := ws.httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
ws.logger.Fatal("cannot start web server", "error", err)
|
|
}
|
|
}()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (ws *WebServer) Stop() error {
|
|
ws.logger.Debug("stopping web server")
|
|
|
|
if err := ws.httpServer.Close(); err != nil {
|
|
return fmt.Errorf("cannot stop web server: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (ws *WebServer) healthHandler(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Fprint(w, "OK")
|
|
}
|
|
|
|
func (ws *WebServer) nextBirthdayHandler(w http.ResponseWriter, r *http.Request) {
|
|
ws.JSON(w, http.StatusOK, ws.server.NextBirthdays())
|
|
}
|
|
|
|
func (ws *WebServer) JSON(w http.ResponseWriter, statusCode int, data any) {
|
|
b, err := json.Marshal(data)
|
|
if err != nil {
|
|
ws.logger.Error("cannot marshal data", "error", err)
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(statusCode)
|
|
w.Write(b)
|
|
}
|