41 lines
844 B
Go
41 lines
844 B
Go
|
|
package handlers
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"net/http"
|
||
|
|
"strconv"
|
||
|
|
|
||
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
||
|
|
)
|
||
|
|
|
||
|
|
type ctxKey string
|
||
|
|
|
||
|
|
const poolKey ctxKey = "pgpool"
|
||
|
|
|
||
|
|
func WithPool(next http.Handler, pool *pgxpool.Pool) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
ctx := context.WithValue(r.Context(), poolKey, pool)
|
||
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
func poolFrom(r *http.Request) *pgxpool.Pool {
|
||
|
|
return r.Context().Value(poolKey).(*pgxpool.Pool)
|
||
|
|
}
|
||
|
|
|
||
|
|
func parsePage(r *http.Request) (page, limit int) {
|
||
|
|
page = 1
|
||
|
|
limit = 20
|
||
|
|
if v := r.URL.Query().Get("page"); v != "" {
|
||
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||
|
|
page = n
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if v := r.URL.Query().Get("limit"); v != "" {
|
||
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 100 {
|
||
|
|
limit = n
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return page, limit
|
||
|
|
}
|