Add initial Go server skeleton with HTTP handlers, middleware, job runner, and stubs
This commit is contained in:
78
internal/http/middleware.go
Normal file
78
internal/http/middleware.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ContextKey used to store values in context
|
||||
type ContextKey string
|
||||
|
||||
const (
|
||||
ContextKeyRequestID ContextKey = "request-id"
|
||||
)
|
||||
|
||||
// RequestID middleware sets a request ID in headers and request context
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Logging middleware prints basic request logs
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
log.Printf("%s %s in %v", r.Method, r.URL.Path, time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
// Auth middleware placeholder to authenticate users
|
||||
func Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Basic dev auth: read X-Auth-User; in real world, validate session/jwt
|
||||
username := r.Header.Get("X-Auth-User")
|
||||
if username == "" {
|
||||
username = "anonymous"
|
||||
}
|
||||
// Role hint: header X-Auth-Role (admin/operator/viewer)
|
||||
role := r.Header.Get("X-Auth-Role")
|
||||
if role == "" {
|
||||
if username == "admin" {
|
||||
role = "admin"
|
||||
} else {
|
||||
role = "viewer"
|
||||
}
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ContextKey("user"), username)
|
||||
ctx = context.WithValue(ctx, ContextKey("user.role"), role)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// CSRF middleware placeholder (reads X-CSRF-Token)
|
||||
func CSRFMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// TODO: check and enforce CSRF tokens for mutating requests
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// RBAC middleware placeholder
|
||||
func RBAC(permission string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Try to read role from context and permit admin always
|
||||
role := r.Context().Value(ContextKey("user.role"))
|
||||
if role == "admin" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// For now, only admin is permitted; add permission checks here
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user