Skip to content

Commit

Permalink
add request Scopes api, the user can add parameters dynamically.
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkgos authored and gogogo committed Mar 18, 2024
1 parent 1792d62 commit ed1f2ea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions request.go
Expand Up @@ -604,6 +604,28 @@ func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request {
return r
}

// Scopes pass current request instance to arguments `func(*Request) *Request`,
// which could be used to add parameters dynamically
// func TransferContentType(r *Request) *Request {
// return r.SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
// }
//
// func PageParam(page, size int) func (r *Request) *Request {
// return func(r *Request) *Request {
// return r.SetQueryParam("page", strconv.FormatInt(int64(page), 10)).
// SetQueryParam("size", strconv.FormatInt(int64(size), 10))
// }
// }
//
// r.Scopes(TransferContentType, PageParam(1, 100)).Get("https://localhost:8080/bar")
func (r *Request) Scopes(funcs ...func(r *Request) *Request) *Request {
for _, f := range funcs {
r = f(r)
}
return r
}

//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// HTTP request tracing
//_______________________________________________________________________
Expand Down
30 changes: 30 additions & 0 deletions request_test.go
Expand Up @@ -937,6 +937,36 @@ func TestGetWithCookies(t *testing.T) {
logResponse(t, resp)
}

func TestRequestScopes(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()

c := dc()
c.SetQueryParam("client_param", "true").
SetQueryParams(map[string]string{"req_1": "jeeva", "req_3": "jeeva3"}).
SetDebug(true)
c.outputLogTo(ioutil.Discard)

queryParam := func(page, size int) func(r *Request) *Request {
return func(r *Request) *Request {
return r.SetQueryParam("page", strconv.FormatInt(int64(page), 10)).
SetQueryParam("size", strconv.FormatInt(int64(size), 10)).
SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10))
}
}
resp, err := c.R().Scopes(queryParam(1, 100)).
SetHeader(hdrUserAgentKey, "Test Custom User agent").
Get(ts.URL + "/")

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "HTTP/1.1", resp.Proto())
assertEqual(t, "200 OK", resp.Status())
assertEqual(t, "TestGet: text response", resp.String())

logResponse(t, resp)
}

func TestPutPlainString(t *testing.T) {
ts := createGenServer(t)
defer ts.Close()
Expand Down

0 comments on commit ed1f2ea

Please sign in to comment.