trigger endpoint and retry suggestions

This commit is contained in:
2026-04-25 15:21:09 +02:00
parent 20ebe5a49f
commit 846083e230
6 changed files with 103 additions and 37 deletions

View File

@@ -28,8 +28,9 @@ type Config struct {
APIEnabled bool `envconfig:"API_ENABLED" default:"true"`
APIPort int `envconfig:"API_PORT" default:"8080"`
RecommendCount int `envconfig:"RECOMMEND_COUNT" default:"10"`
MinRatedMovies int `envconfig:"MIN_RATED_MOVIES" default:"5"`
RecommendCount int `envconfig:"RECOMMEND_COUNT" default:"10"`
RecommendMaxRetry int `envconfig:"RECOMMEND_MAX_RETRY" default:"3"`
MinRatedMovies int `envconfig:"MIN_RATED_MOVIES" default:"5"`
}
// Load reads .env (best-effort) then processes environment variables into a Config.

View File

@@ -3,6 +3,7 @@ package httputil
import (
"encoding/json"
"net/http"
"strings"
)
func WriteJSON(w http.ResponseWriter, status int, v any) {
@@ -14,3 +15,21 @@ func WriteJSON(w http.ResponseWriter, status int, v any) {
func WriteError(w http.ResponseWriter, status int, msg string) {
WriteJSON(w, status, map[string]string{"error": msg})
}
// AuthMiddleware validates the Authorization: Bearer <key> header.
// If secretKey is empty, auth is disabled and all requests pass through.
// /health is always exempt.
func AuthMiddleware(secretKey string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if secretKey == "" || r.URL.Path == "/health" {
next.ServeHTTP(w, r)
return
}
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token != secretKey {
WriteError(w, http.StatusUnauthorized, "unauthorized")
return
}
next.ServeHTTP(w, r)
})
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/fjurmanovic/sugarr/internal/api"
"github.com/fjurmanovic/sugarr/internal/service"
"github.com/fjurmanovic/sugarr/internal/utl/configs"
"github.com/fjurmanovic/sugarr/internal/utl/httputil"
"github.com/rs/zerolog/log"
)
@@ -17,5 +18,8 @@ func Start(cfg *configs.Config, rec *service.Recommender) error {
addr := fmt.Sprintf(":%d", cfg.APIPort)
log.Info().Msgf("HTTP API listening on %s", addr)
return http.ListenAndServe(addr, mux)
if cfg.APISecretKey != "" {
log.Info().Msg("Secret key auth enabled")
}
return http.ListenAndServe(addr, httputil.AuthMiddleware(cfg.APISecretKey, mux))
}