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) } }