Initial commit.
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
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) {
|
||||
h.httpMux.HandleFunc(fmt.Sprintf("%s %s", method, path), func(w http.ResponseWriter, r *http.Request) {
|
||||
for i := len(h.middlewares) - 1; i >= 0; i-- {
|
||||
handler = h.middlewares[i](handler)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user