Initial commit.
Linting and tests / Linting (push) Failing after 30s
Linting and tests / Tests (push) Successful in 25s

This commit is contained in:
2026-06-10 10:23:00 +05:00
commit 3d43b8a84e
34 changed files with 1325 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
package core
import (
"errors"
"net/http"
)
// ServiceNameHTTPServer is a name for HTTP server service.
const ServiceNameHTTPServer = "core/http_server"
// ErrHTTPServerIsInvalid appears when HTTP server service implementation is invalid.
var ErrHTTPServerIsInvalid = errors.New("HTTP server service implementation is invalid")
// HTTPServer is an interface for HTTP server service.
type HTTPServer interface {
// RegisterHandler registers HTTP handler.
RegisterHandler(method, path string, handler http.HandlerFunc)
// RegisterMiddleware registers HTTP server middlewares.
RegisterMiddleware(middleware HTTPMiddlewareFunc)
}
// HTTPMiddlewareFunc is a function that acts as middleware for HTTP requests.
type HTTPMiddlewareFunc func(fn http.HandlerFunc) http.HandlerFunc
@@ -0,0 +1,8 @@
package httpserver
import "net/http"
func (h *httpServer) defaultHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("Unknown path."))
}
@@ -0,0 +1,84 @@
package httpserver
import (
"errors"
"fmt"
"log/slog"
"net/http"
"go.dev.pztrn.name/vikunja-notifier/internal/application"
"go.dev.pztrn.name/vikunja-notifier/internal/services/core"
)
var (
_ = core.HTTPServer(&httpServer{})
errHTTPServer = errors.New("HTTP server core service")
)
type httpServer struct {
app *application.Application
logger *slog.Logger
httpSrv *http.Server
httpMux *http.ServeMux
middlewares []core.HTTPMiddlewareFunc
}
// Initialize initializes service.
func Initialize(app *application.Application) error {
httpSrv := &httpServer{
app: app,
}
if err := app.RegisterService(httpSrv); err != nil {
return fmt.Errorf("%w: %w", errHTTPServer, err)
}
return nil
}
func (h *httpServer) Configure() error {
h.logger.Debug("Configuring service...")
if err := h.configureHTTPServer(); err != nil {
return fmt.Errorf("configure: %w", err)
}
return nil
}
func (h *httpServer) ConnectDependencies() error {
return nil
}
func (h *httpServer) Initialize() error {
h.logger = h.app.NewLogger("service", core.ServiceNameHTTPServer)
h.logger.Info("Initializing...")
h.middlewares = make([]core.HTTPMiddlewareFunc, 0)
h.RegisterMiddleware(h.requestLoggingMiddleware)
return nil
}
func (h *httpServer) Name() string {
return core.ServiceNameHTTPServer
}
func (h *httpServer) LaunchStartupTasks() error {
h.logger.Debug("Launching startup tasks...")
go h.startHTTPServer()
return nil
}
func (h *httpServer) Shutdown() error {
if err := h.stopHTTPServer(); err != nil {
return fmt.Errorf("%w: Shutdown: %w", errHTTPServer, err)
}
return nil
}
@@ -0,0 +1,24 @@
package httpserver
import (
"fmt"
"net/http"
"time"
)
func (h *httpServer) requestLoggingMiddleware(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
fn(w, r)
h.logger.Info(
"HTTP request.",
"remote_addr", r.RemoteAddr,
"user_agent", r.UserAgent(),
"host", r.Host,
"path", fmt.Sprintf("%s %s", r.Method, r.RequestURI),
"duration", time.Since(startTime),
)
}
}
@@ -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
}