forked from rs/rest-layer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method_get.go
96 lines (92 loc) · 2.36 KB
/
method_get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package rest
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/rs/rest-layer/resource"
)
// listGet handles GET resquests on a resource URL
func listGet(ctx context.Context, r *http.Request, route *RouteMatch) (status int, headers http.Header, body interface{}) {
offset := 0
limit := 0
rsrc := route.Resource()
if route.Method != "HEAD" {
if l := rsrc.Conf().PaginationDefaultLimit; l > 0 {
limit = l
} else {
// Default value on non HEAD request for limit is -1 (pagination disabled)
limit = -1
}
if l, found, err := getUintParam(route.Params, "limit"); found {
if err != nil {
return 422, nil, err
}
limit = l
}
skip := 0
if s, found, err := getUintParam(route.Params, "skip"); found {
if err != nil {
return 422, nil, err
}
skip = s
}
page := 1
if p, found, err := getUintParam(route.Params, "page"); found {
if err != nil {
return 422, nil, err
}
page = p
}
if page > 1 && limit <= 0 {
return 422, nil, &Error{422, "Cannot use `page' parameter with no `limit' parameter on a resource with no default pagination size", nil}
}
offset = (page-1)*limit + skip
}
forceTotal := false
switch rsrc.Conf().ForceTotal {
case resource.TotalOptIn:
forceTotal = route.Params.Get("total") == "1"
case resource.TotalAlways:
forceTotal = true
case resource.TotalDenied:
if route.Params.Get("total") == "1" {
return 422, nil, &Error{422, "Cannot use `total' parameter: denied by configuration", nil}
}
}
lookup, e := route.Lookup()
if e != nil {
return e.Code, nil, e
}
var list *resource.ItemList
var err error
if forceTotal {
list, err = rsrc.FindWithTotal(ctx, lookup, offset, limit)
} else {
list, err = rsrc.Find(ctx, lookup, offset, limit)
}
if err != nil {
e = NewError(err)
return e.Code, nil, e
}
list.Offset = offset
for _, item := range list.Items {
item.Payload, err = lookup.ApplySelector(ctx, rsrc.Validator(), item.Payload, getReferenceResolver(ctx, rsrc))
if err != nil {
e = NewError(err)
return e.Code, nil, e
}
}
return 200, nil, list
}
func getUintParam(params url.Values, name string) (int, bool, error) {
if v := params.Get(name); v != "" {
i, err := strconv.ParseUint(v, 10, 32)
if err != nil {
return 0, true, &Error{422, fmt.Sprintf("Invalid `%s` parameter", name), nil}
}
return int(i), true, nil
}
return 0, false, nil
}