From ed1f2ea47b65f4f21eea400f1816768085d0f6d8 Mon Sep 17 00:00:00 2001 From: thinkgo Date: Fri, 17 Sep 2021 14:35:26 +0800 Subject: [PATCH] add request Scopes api, the user can add parameters dynamically. --- request.go | 22 ++++++++++++++++++++++ request_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/request.go b/request.go index 52166e69..cf0b8565 100644 --- a/request.go +++ b/request.go @@ -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 //_______________________________________________________________________ diff --git a/request_test.go b/request_test.go index 3d0dc262..43072d8c 100644 --- a/request_test.go +++ b/request_test.go @@ -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()