Files
vikunja-notifier/internal/services/core/httpserver/server.go
T
pztrn 7cc06a9ef1
Linting and tests / Linting (push) Successful in 19s
Linting and tests / Tests (push) Successful in 17s
Improve HTTP server.
2026-06-10 10:39:12 +05:00

83 lines
2.2 KiB
Go

package httpserver
import (
"errors"
"fmt"
"net"
"net/http"
"os"
"time"
"go.dev.pztrn.name/vikunja-notifier/internal/services/core"
)
const httpServerAddrEnvVar = "VN_HTTP_ADDRESS"
var (
errHTTPServerAddrInvalid = errors.New("VN_HTTP_ADDRESS environment variable contains invalid address to " +
"listen, should be 'host:port'")
errHTTPServerAddrNotFound = errors.New("VN_HTTP_ADDRESS environment variable empty")
)
func (h *httpServer) configureHTTPServer() error {
httpSrvAddr, found := os.LookupEnv(httpServerAddrEnvVar)
if !found {
return fmt.Errorf("configure HTTP server: get address from environment variable: %w", errHTTPServerAddrNotFound)
}
host, port, err := net.SplitHostPort(httpSrvAddr)
if err != nil {
return fmt.Errorf("configure HTTP server: validate HTTP server address: %w", err)
}
if httpSrvAddr != host+":"+port {
return fmt.Errorf("configure HTTP server: validate HTTP server address: %w", errHTTPServerAddrInvalid)
}
h.httpMux = new(http.ServeMux)
// Default catch-all handler.
h.RegisterHandler("", "/", h.defaultHandler)
h.httpSrv = &http.Server{
Addr: httpSrvAddr,
Handler: h.httpMux,
ReadHeaderTimeout: time.Second * 3,
}
return nil
}
func (h *httpServer) RegisterHandler(method, path string, handler http.HandlerFunc) {
//nolint:modernize
for i := len(h.middlewares) - 1; i >= 0; i-- {
handler = h.middlewares[i](handler)
}
h.httpMux.HandleFunc(fmt.Sprintf("%s %s", method, path), func(w http.ResponseWriter, r *http.Request) {
handler(w, r)
})
}
func (h *httpServer) RegisterMiddleware(middleware core.HTTPMiddlewareFunc) {
h.middlewares = append(h.middlewares, middleware)
}
func (h *httpServer) startHTTPServer() {
h.logger.Info("Starting listening for HTTP requests.", "address", h.httpSrv.Addr)
if err := h.httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
h.logger.Warn("Error when listening to ", "error", err.Error())
}
}
func (h *httpServer) stopHTTPServer() error {
h.logger.Info("Stopping HTTP server...")
if err := h.httpSrv.Shutdown(h.app.ContextWithTimeout(time.Second * 3)); err != nil {
return fmt.Errorf("stopping HTTP server: %w", err)
}
return nil
}