MCPcopy
hub / github.com/gofiber/fiber / New

Function New

middleware/paginate/paginate.go:27–87  ·  view source on GitHub ↗

New creates a new pagination middleware handler.

(config ...Config)

Source from the content-addressed store, hash-verified

25
26// New creates a new pagination middleware handler.
27func New(config ...Config) fiber.Handler {
28 cfg := configDefault(config...)
29
30 return func(c fiber.Ctx) error {
31 if cfg.Next != nil && cfg.Next(c) {
32 return c.Next()
33 }
34
35 appCfg := c.App().Config()
36
37 limit := fiber.Query(c, cfg.LimitKey, cfg.DefaultLimit)
38 if limit < 1 {
39 limit = cfg.DefaultLimit
40 }
41 if limit > cfg.MaxLimit {
42 limit = cfg.MaxLimit
43 }
44
45 sorts := parseSortQuery(c.Query(cfg.SortKey), cfg.AllowedSorts, cfg.DefaultSort)
46
47 cursorRaw := c.Query(cfg.CursorKey)
48 if cursorRaw == "" && cfg.CursorParam != "" {
49 cursorRaw = c.Query(cfg.CursorParam)
50 }
51
52 if cursorRaw != "" {
53 if len(cursorRaw) > maxCursorLen {
54 return fiber.NewError(fiber.StatusBadRequest, "cursor too long")
55 }
56
57 data, err := base64.RawURLEncoding.DecodeString(cursorRaw)
58 if err != nil {
59 return fiber.NewError(fiber.StatusBadRequest, "invalid cursor")
60 }
61 var obj map[string]any
62 if err := appCfg.JSONDecoder(data, &obj); err != nil {
63 return fiber.NewError(fiber.StatusBadRequest, "invalid cursor")
64 }
65
66 pageInfo := &PageInfo{
67 Limit: limit,
68 Sort: sorts,
69 Cursor: cursorRaw,
70 cursorData: obj,
71 jsonMarshal: appCfg.JSONEncoder,
72 jsonUnmarshal: appCfg.JSONDecoder,
73 }
74 fiber.StoreInContext(c, pageInfoKey, pageInfo)
75 return c.Next()
76 }
77
78 page := max(fiber.Query(c, cfg.PageKey, cfg.DefaultPage), 1)
79 offset := max(fiber.Query(c, cfg.OffsetKey, 0), 0)
80
81 pageInfo := NewPageInfo(page, limit, offset, sorts)
82 pageInfo.jsonMarshal = appCfg.JSONEncoder
83 pageInfo.jsonUnmarshal = appCfg.JSONDecoder
84 fiber.StoreInContext(c, pageInfoKey, pageInfo)

Calls 7

parseSortQueryFunction · 0.85
NewPageInfoFunction · 0.85
configDefaultFunction · 0.70
NextMethod · 0.65
ConfigMethod · 0.65
AppMethod · 0.65
QueryMethod · 0.65