feat: add books APIs

This commit is contained in:
gosangam
2026-05-09 23:19:19 +05:30
commit b055b8ba0c
43 changed files with 4307 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
package middleware
import (
"context"
"net/http"
"strings"
"github.com/prabhupadasays/spsays-bff/pkg/response"
)
type contextKey string
const UserIDKey contextKey = "user_id"
// Auth is a placeholder middleware for JWT authentication.
// It extracts the Bearer token from the Authorization header,
// validates it, and sets the user ID in the request context.
func Auth(jwtSecret string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
response.Error(w, http.StatusUnauthorized, "missing authorization header")
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
response.Error(w, http.StatusUnauthorized, "invalid authorization format")
return
}
token := parts[1]
// TODO: validate JWT token and extract user ID
_ = token
_ = jwtSecret
userID := "" // placeholder
if userID == "" {
response.Error(w, http.StatusUnauthorized, "invalid or expired token")
return
}
ctx := context.WithValue(r.Context(), UserIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetUserID extracts the user ID from the request context.
func GetUserID(ctx context.Context) string {
if v, ok := ctx.Value(UserIDKey).(string); ok {
return v
}
return ""
}
+32
View File
@@ -0,0 +1,32 @@
package middleware
import (
"net/http"
"time"
chiMiddleware "github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)
// Logger returns a chi-compatible middleware that logs requests using zap.
func Logger(logger *zap.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := chiMiddleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
logger.Info("request",
zap.String("method", r.Method),
zap.String("path", r.URL.Path),
zap.String("query", r.URL.RawQuery),
zap.Int("status", ww.Status()),
zap.Int("bytes", ww.BytesWritten()),
zap.Duration("duration", time.Since(start)),
zap.String("ip", r.RemoteAddr),
zap.String("request_id", chiMiddleware.GetReqID(r.Context())),
)
})
}
}
+81
View File
@@ -0,0 +1,81 @@
package middleware
import (
"net/http"
"sync"
"time"
"github.com/prabhupadasays/spsays-bff/pkg/response"
)
// RateLimiter is a simple in-memory token bucket rate limiter.
// In production, replace with DragonflyDB/Redis-based limiter.
type RateLimiter struct {
mu sync.Mutex
visitors map[string]*visitor
rate int // tokens per interval
interval time.Duration // refill interval
}
type visitor struct {
tokens int
lastSeen time.Time
}
// NewRateLimiter creates a new in-memory rate limiter.
func NewRateLimiter(rate int, interval time.Duration) *RateLimiter {
rl := &RateLimiter{
visitors: make(map[string]*visitor),
rate: rate,
interval: interval,
}
// Clean up stale visitors every minute
go rl.cleanup()
return rl
}
// Limit returns a middleware that rate-limits requests by IP.
func (rl *RateLimiter) Limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
rl.mu.Lock()
v, exists := rl.visitors[ip]
if !exists {
v = &visitor{tokens: rl.rate, lastSeen: time.Now()}
rl.visitors[ip] = v
}
// Refill tokens
elapsed := time.Since(v.lastSeen)
refill := int(elapsed / rl.interval)
if refill > 0 {
v.tokens = min(v.tokens+refill*rl.rate, rl.rate)
v.lastSeen = time.Now()
}
if v.tokens <= 0 {
rl.mu.Unlock()
response.Error(w, http.StatusTooManyRequests, "rate limit exceeded")
return
}
v.tokens--
rl.mu.Unlock()
next.ServeHTTP(w, r)
})
}
func (rl *RateLimiter) cleanup() {
for {
time.Sleep(time.Minute)
rl.mu.Lock()
for ip, v := range rl.visitors {
if time.Since(v.lastSeen) > 3*time.Minute {
delete(rl.visitors, ip)
}
}
rl.mu.Unlock()
}
}