Files
calculate_negative_points/internal/api/middleware/pagination.go
Eugene Howe b0957bfa49
Some checks failed
Docker Build and Publish / publish (push) Failing after 1m33s
webapp
2026-02-17 09:47:30 -05:00

49 lines
925 B
Go

package middleware
import (
"context"
"net/http"
"strconv"
)
type Pagination struct {
Page int
PageSize int
}
const PaginationContextKey = "pagination"
func PaginationMiddleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
page := 1
pageSize := 20
if p := r.URL.Query().Get("page"); p != "" {
if parsed, err := strconv.Atoi(p); err == nil && parsed >= 1 {
page = parsed
}
}
if ps := r.URL.Query().Get("page_size"); ps != "" {
if parsed, err := strconv.Atoi(ps); err == nil && parsed >= 1 {
pageSize = parsed
}
}
if pageSize > 100 {
pageSize = 100
}
ctx := context.WithValue(r.Context(), PaginationContextKey, Pagination{
Page: page,
PageSize: pageSize,
})
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
}