Skip to content

Commit

Permalink
feat: add GetQueryParam method to support pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Kistler committed Mar 11, 2021
1 parent 1cbe850 commit e6528df
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
25 changes: 25 additions & 0 deletions v5/core/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"reflect"
"regexp"
Expand Down Expand Up @@ -261,3 +262,27 @@ func SliceContains(slice []string, contains string) bool {
}
return false
}

// return a pointer to the value of query parameter `param` from url,
// or nil when not found
func GetQueryParam(urlStr *string, param string) (*string, error) {
if urlStr == nil || *urlStr == "" {
return nil, nil
}

u, err := url.Parse(*urlStr)
if err != nil {
return nil, err
}

q, err := url.ParseQuery(u.RawQuery)
if err != nil {
return nil, err
}

v := q.Get(param)
if v == "" {
return nil, nil
}
return &v, nil
}
52 changes: 52 additions & 0 deletions v5/core/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -480,3 +480,55 @@ func TestSliceContains(t *testing.T) {

assert.False(t, SliceContains(nil, "foo"))
}

func TestGetQueryParam(t *testing.T) {
nextURL := "/api/v1/offerings?start=foo&limit=10"
next, err := GetQueryParam(&nextURL, "start")
assert.Nil(t, err)
assert.Equal(t, "foo", *next)

fqNextURL := "https://acme.com/api/v1/offerings?start=bar&limit=10"
next, err = GetQueryParam(&fqNextURL, "start")
assert.Nil(t, err)
assert.Equal(t, "bar", *next)

// No query parameter
next, err = GetQueryParam(&nextURL, "token")
assert.Nil(t, err)
assert.Nil(t, next)

// nil URL
next, err = GetQueryParam(nil, "start")
assert.Nil(t, err)
assert.Nil(t, next)

// empty URL
var emptyURL string
next, err = GetQueryParam(&emptyURL, "start")
assert.Nil(t, err)
assert.Nil(t, next)

// Not a URL (parse fails)
badURL := "https://foo.bar:baz/api/v1/offerings?start=foo"
next, err = GetQueryParam(&badURL, "start")
assert.NotNil(t, err)
assert.Nil(t, next)

// No query string
noQueryStringURL := "/api/v1/offerings"
next, err = GetQueryParam(&noQueryStringURL, "start")
assert.Nil(t, err)
assert.Nil(t, next)

// Bad query string
badQueryURL := "/api/v1/offerings?start%XXfoo"
next, err = GetQueryParam(&badQueryURL, "start")
assert.NotNil(t, err)
assert.Nil(t, next)

// Duplicate param
dupParamURL := "/api/v1/offerings?start=foo&start=bar&limit=10"
next, err = GetQueryParam(&dupParamURL, "start")
assert.Nil(t, err)
assert.Equal(t, "foo", *next)
}

0 comments on commit e6528df

Please sign in to comment.