Skip to content

Commit 2ec20f7

Browse files
committed
Factorize parameter parsing code
1 parent 27a91bb commit 2ec20f7

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

rest/method_get.go

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package rest
22

33
import (
44
"context"
5+
"fmt"
56
"net/http"
7+
"net/url"
68
"strconv"
79
)
810

@@ -18,31 +20,28 @@ func listGet(ctx context.Context, r *http.Request, route *RouteMatch) (status in
1820
// Default value on non HEAD request for limit is -1 (pagination disabled)
1921
limit = -1
2022
}
21-
if l := route.Params.Get("limit"); l != "" {
22-
i, err := strconv.ParseUint(l, 10, 32)
23+
if l, found, err := getUintParam(route.Params, "limit"); found {
2324
if err != nil {
24-
return 422, nil, &Error{422, "Invalid `limit` parameter", nil}
25+
return 422, nil, err
2526
}
26-
limit = int(i)
27+
limit = l
2728
}
2829
skip := 0
29-
if o := route.Params.Get("skip"); o != "" {
30-
i, err := strconv.ParseUint(o, 10, 32)
30+
if s, found, err := getUintParam(route.Params, "skip"); found {
3131
if err != nil {
32-
return 422, nil, &Error{422, "Invalid `skip` parameter", nil}
32+
return 422, nil, err
3333
}
34-
skip = int(i)
34+
skip = s
3535
}
3636
page := 1
37-
if p := route.Params.Get("page"); p != "" {
38-
i, err := strconv.ParseUint(p, 10, 32)
37+
if p, found, err := getUintParam(route.Params, "page"); found {
3938
if err != nil {
40-
return 422, nil, &Error{422, "Invalid `page` parameter", nil}
41-
}
42-
page = int(i)
43-
if limit <= 0 {
44-
return 422, nil, &Error{422, "Cannot use `page' parameter with no `limit' parameter on a resource with no default pagination size", nil}
39+
return 422, nil, err
4540
}
41+
page = p
42+
}
43+
if page > 1 && limit <= 0 {
44+
return 422, nil, &Error{422, "Cannot use `page' parameter with no `limit' parameter on a resource with no default pagination size", nil}
4645
}
4746
offset = (page-1)*limit + skip
4847
}
@@ -65,3 +64,14 @@ func listGet(ctx context.Context, r *http.Request, route *RouteMatch) (status in
6564
}
6665
return 200, nil, list
6766
}
67+
68+
func getUintParam(params url.Values, name string) (int, bool, error) {
69+
if v := params.Get(name); v != "" {
70+
i, err := strconv.ParseUint(v, 10, 32)
71+
if err != nil {
72+
return 0, true, &Error{422, fmt.Sprintf("Invalid `%s` parameter", name), nil}
73+
}
74+
return int(i), true, nil
75+
}
76+
return 0, false, nil
77+
}

0 commit comments

Comments
 (0)