birthdaybot/server/web.go

77 lines
1.6 KiB
Go
Raw Normal View History

2023-07-11 11:37:56 +01:00
package server
import (
2023-07-11 12:27:50 +01:00
"encoding/json"
2023-07-11 11:37:56 +01:00
"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)
2023-07-11 12:27:50 +01:00
mux.HandleFunc("/next_birthdays", ws.nextBirthdayHandler)
2023-07-11 11:37:56 +01:00
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")
}
2023-07-11 12:27:50 +01:00
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)
}