58 lines
1 KiB
Go
58 lines
1 KiB
Go
package server
|
|
|
|
import (
|
|
"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)
|
|
|
|
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")
|
|
}
|