Initial commit
This commit is contained in:
64
middleware.go
Normal file
64
middleware.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// List of public endpoint paths
|
||||
var publicEndpoints = []string{
|
||||
"/api/v1/health",
|
||||
"/swagger",
|
||||
}
|
||||
|
||||
// Middleware for logging
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
log.Printf("[%s] %s %s", r.Method, r.URL.Path, r.RemoteAddr)
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf("Completed in %v", time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
// Checks if a path matches any public endpoint
|
||||
func isPublicEndpoint(path string) bool {
|
||||
for _, endpoint := range publicEndpoints {
|
||||
if path == endpoint || strings.HasPrefix(path, endpoint) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Middleware that handles auth
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Skip auth for public endpoints
|
||||
if isPublicEndpoint(r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
validAPIKey := os.Getenv("API_KEY")
|
||||
if validAPIKey == "" {
|
||||
log.Println(
|
||||
"WARNING: API_KEY environment variable not set, using default",
|
||||
)
|
||||
validAPIKey = "secret-key"
|
||||
}
|
||||
|
||||
apiKey := r.Header.Get("X-API-Key")
|
||||
if apiKey != validAPIKey {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"error":"unauthorized"}`))
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user