Skip to content

Commit

Permalink
fix(curl): getCurlCmd should not send request
Browse files Browse the repository at this point in the history
  • Loading branch information
ahuigo committed Oct 14, 2023
1 parent fa336ff commit 606416e
Show file tree
Hide file tree
Showing 22 changed files with 107 additions and 76 deletions.
23 changes: 15 additions & 8 deletions client.go
Expand Up @@ -1129,9 +1129,7 @@ func (c *Client) GetClient() *http.Client {
// Client Unexported methods
//_______________________________________________________________________

// Executes method executes the given `Request` object and returns response
// error.
func (c *Client) execute(req *Request) (*Response, error) {
func (c *Client) executeBefore(req *Request) (error) {
// Lock the user-defined pre-request hooks.
c.udBeforeRequestLock.RLock()
defer c.udBeforeRequestLock.RUnlock()
Expand All @@ -1147,22 +1145,22 @@ func (c *Client) execute(req *Request) (*Response, error) {
// to modify the *resty.Request object
for _, f := range c.udBeforeRequest {
if err = f(c, req); err != nil {
return nil, wrapNoRetryErr(err)
return wrapNoRetryErr(err)
}
}

// If there is a rate limiter set for this client, the Execute call
// will return an error if the rate limit is exceeded.
if req.client.rateLimiter != nil {
if !req.client.rateLimiter.Allow() {
return nil, wrapNoRetryErr(ErrRateLimitExceeded)
return wrapNoRetryErr(ErrRateLimitExceeded)
}
}

// resty middlewares
for _, f := range c.beforeRequest {
if err = f(c, req); err != nil {
return nil, wrapNoRetryErr(err)
return wrapNoRetryErr(err)
}
}

Expand All @@ -1173,15 +1171,24 @@ func (c *Client) execute(req *Request) (*Response, error) {
// call pre-request if defined
if c.preReqHook != nil {
if err = c.preReqHook(c, req.RawRequest); err != nil {
return nil, wrapNoRetryErr(err)
return wrapNoRetryErr(err)
}
}

if err = requestLogger(c, req); err != nil {
return nil, wrapNoRetryErr(err)
return wrapNoRetryErr(err)
}

req.RawRequest.Body = newRequestBodyReleaser(req.RawRequest.Body, req.bodyBuf)
return nil
}

// Executes method executes the given `Request` object and returns response
// error.
func (c *Client) execute(req *Request) (*Response, error) {
if err:= c.executeBefore(req);err!=nil{
return nil, err
}

req.Time = time.Now()
resp, err := c.httpClient.Do(req.RawRequest)
Expand Down
17 changes: 12 additions & 5 deletions examples/auth_test.go
Expand Up @@ -7,19 +7,26 @@ import (
"github.com/go-resty/resty/v3"
)


// Example about sending Authentication header
func TestAuth(t *testing.T) {
var curlCmdExecuted string
ts := createEchoServer()
defer ts.Close()
// test authentication usernae,password
// Test authentication usernae and password
client := resty.New()
resp, err := client.R().SetBasicAuth("httpwatch", "foo").Get( ts.URL+"/echo",)
resp, err := client.R().
SetBasicAuth("httpwatch", "foo").
SetResultCurlCmd(&curlCmdExecuted).
Get( ts.URL+"/echo",)
if err != nil {
t.Fatal(err)
}

if !strings.Contains(curlCmdExecuted, "Authorization: Basic ") {
t.Fatal("bad curl:", curlCmdExecuted)
}
if !strings.Contains(string(resp.Body()), "Authorization: Basic ") {
t.Fatal("bad auth body:\n" + resp.String())
}
// this save file test PASS
// resp.SaveFile("auth.jpeg")
t.Log(curlCmdExecuted)
}
14 changes: 6 additions & 8 deletions examples/context_test.go
@@ -1,6 +1,3 @@
/**
* refer to: git@github.com:go-resty/resty.git
*/
package examples

import (
Expand All @@ -13,8 +10,9 @@ import (
"github.com/go-resty/resty/v3"
)

// test context: cancel multi
// Example about cancel request with context
func TestSetContextCancelMulti(t *testing.T) {
// 0. Init test server
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Microsecond)
n, err := w.Write([]byte("TestSetContextCancel: response"))
Expand All @@ -23,28 +21,28 @@ func TestSetContextCancelMulti(t *testing.T) {
}, 0)
defer ts.Close()

// client
// 1. Create client
ctx, cancel := context.WithCancel(context.Background())
client := resty.New().R().SetContext(ctx)
go func() {
time.Sleep(1 * time.Microsecond)
cancel()
}()

// first
// 2. First request
_, err := client.Get(ts.URL + "/get")
if !errIsContextCancel(err) {
t.Fatalf("Got unexpected error: %v", err)
}

// second
// 3. Second request
_, err = client.Get(ts.URL + "/get")
if !errIsContextCancel(err) {
t.Fatalf("Got unexpected error: %v", err)
}
}

// test context: cancel with chan
// Test context: cancel with chan
func TestSetContextCancelWithChan(t *testing.T) {
ch := make(chan struct{})
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
Expand Down
15 changes: 8 additions & 7 deletions examples/cookie_test.go
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/go-resty/resty/v3"
)

// Example about sending cookie
func TestSendCookie(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand Down Expand Up @@ -84,7 +85,7 @@ func TestSessionCookieWithClone(t *testing.T) {
client := resty.New()
req := client.R()

// set cookie
// 0. Prepare cookie1 and cookie2
cookie1 := &http.Cookie{
Name: "name1",
Value: "value1",
Expand All @@ -95,26 +96,28 @@ func TestSessionCookieWithClone(t *testing.T) {
Value: "value2",
}

// 1. set cookie1
// 1. Set cookie1
client.SetCookie(cookie1)
req.SetCookie(cookie1).Get(url)

// 2. set cookie2 and get all cookies
// 2. Set cookie2 and get all cookies
resp, err := req.SetCookie(cookie2).Get(url)
if err != nil {
t.Fatal(err)
}

// 3. check cookies: client, response
// 3. Check cookies: client and response
respCookies := map[string]string{}
clientCookies := map[string]string{}
// cookies's type is `[]*http.Cookies`
// 3.1 Check response cookies
for _, c := range resp.Cookies() {
if _, exists := respCookies[c.Name]; exists {
t.Fatal("duplicated cookie:", c.Name, c.Value)
}
respCookies[c.Name] = c.Value
}
// 3.2 Check client cookies
for _, c := range client.Cookies {
if _, exists := clientCookies[c.Name]; exists {
t.Fatal("duplicated cookie:", c.Name, c.Value)
Expand All @@ -125,7 +128,7 @@ func TestSessionCookieWithClone(t *testing.T) {
t.Fatalf("bad cookie, respCookies=%+v, clientCookies=%+v", resp.Cookies(), client.Cookies)
}

// 4. check response body
// 4. Check response body
body := resp.String()
if (!strings.Contains(body, `"name1"`) ||
!strings.Contains(body, `"name2"`) ||
Expand All @@ -140,8 +143,6 @@ func TestResponseCookie(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()

// resp, err := requests.Get("https://httpbin.org/json")

session := resty.New().R()
resp, err := session.Get(ts.URL + "/cookie/count")
if err != nil {
Expand Down
26 changes: 12 additions & 14 deletions examples/debug_curl_test.go
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/go-resty/resty/v3"
)


// Example about generating curl command
func TestDebugCurl(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand All @@ -19,23 +19,21 @@ func TestDebugCurl(t *testing.T) {
[]*http.Cookie{
{ Name: "count", Value: "1", },
},
).EnableCurl()
)

// 1. generate curl before request
curl_before_req := req.GetCurlCmd()
if !strings.Contains(curl_before_req, "Cookie: count=1") || !strings.Contains(curl_before_req, "curl -X GET") {
t.Fatal("bad curl:", curl_before_req)
// 1. Generate curl for request(not executed)
curlCmdUnexecuted := req.GetCurlCmd()
if !strings.Contains(curlCmdUnexecuted, "Cookie: count=1") || !strings.Contains(curlCmdUnexecuted, "curl -X GET") {
t.Fatal("bad curl:", curlCmdUnexecuted)
}

// 2. send request
resp, err := req.Post(ts.URL+"/post",)
if err != nil {
// 2. Generate curl for request(executed)
var curlCmdExecuted string
req.SetResultCurlCmd(&curlCmdExecuted)
if _, err := req.Post(ts.URL+"/post"); err != nil {
t.Fatal(err)
}

// 3. generate curl after request
curl_after_req := resp.Request.GetCurlCmd()
if !strings.Contains(curl_after_req, "Cookie: count=1") || !strings.Contains(curl_after_req, "curl -X POST") {
t.Fatal("bad curl:", curl_after_req)
if !strings.Contains(curlCmdExecuted, "Cookie: count=1") || !strings.Contains(curlCmdExecuted, "curl -X POST") {
t.Fatal("bad curl:", curlCmdExecuted)
}
}
2 changes: 1 addition & 1 deletion examples/debug_test.go
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/go-resty/resty/v3"
)


// Example about debuging/showing request and response
func TestDebugRequestAndResponse(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand Down
5 changes: 1 addition & 4 deletions examples/debug_trace_test.go
@@ -1,6 +1,3 @@
/**
* refer to: git@github.com:go-resty/resty.git
*/
package examples

import (
Expand All @@ -9,7 +6,7 @@ import (
"github.com/go-resty/resty/v3"
)

// test context: cancel multi
// Example about getting trace info
func TestTrace(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand Down
2 changes: 1 addition & 1 deletion examples/delete_test.go
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/go-resty/resty/v3"
)

// Delete Form Request
// Example about DELETE method with Form Request
func TestDeleteForm(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand Down
1 change: 1 addition & 0 deletions examples/error_test.go
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/go-resty/resty/v3"
)

// Example about error handling
func TestErrorConnnect(t *testing.T) {
_, err := resty.New().R().Get("http://127.0.0.1:12346/connect-refused")
var err2 *url.Error
Expand Down
2 changes: 2 additions & 0 deletions examples/get_test.go
Expand Up @@ -9,6 +9,8 @@ import (

var client = resty.New()

// Example about sending GET request

// Get example: fetch json response
func TestGetJson(t *testing.T) {
ts := createHttpbinServer(0)
Expand Down
8 changes: 4 additions & 4 deletions examples/post_file_test.go
Expand Up @@ -8,8 +8,8 @@ import (
)

/*
An example about post both `file` and `form data`:
curl "https://www.httpbin.org/post" -F 'file1=@./test-file.txt' -F 'file2=@./version' -F 'name=alex'
An example about post `file` with `form data`:
curl "https://www.httpbin.org/post" -F 'file1=@./test-file.txt' -F 'name=alex'
*/
func TestPostFile(t *testing.T) {
ts := createHttpbinServer(0)
Expand All @@ -30,13 +30,13 @@ func TestPostFile(t *testing.T) {
SetFile("file1", filepath.Join(getTestDataPath(),"text-file.txt")).
SetResult(&data)

// 2. post file
// 2. Post file
resp, err := r.Post( ts.URL+"/file",)
if err != nil {
t.Fatal(err)
}

// 3. check response
// 3. Check response
if data.Files.File1 == "" {
t.Error("invalid response files:", resp.String())
}
Expand Down
2 changes: 2 additions & 0 deletions examples/post_test.go
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/go-resty/resty/v3"
)

// Example about sending POST request

// Post Params: use <QueryString> with content-type: none
// curl -X POST "https://www.httpbin.org/post?name=Alex"
func TestPostParams(t *testing.T) {
Expand Down
21 changes: 15 additions & 6 deletions examples/proxy_test.go
Expand Up @@ -2,13 +2,22 @@ package examples

import (
"testing"

"github.com/go-resty/resty/v3"
)

// Example about using proxy
func TestProxy(t *testing.T) {
println("5. Get: with proxy")
/* todo
session := requests.R()
session.SetProxy("http://192.168.1.190:8888")
session.Get("https://www.httpbin.org/cookies/set?freeform=1234")
*/
ts := createHttpbinServer(0)
defer ts.Close()

var json map[string]interface{}
client := resty.New().SetProxy("http://proxy:8888")
client.RemoveProxy() // remove proxy. TODO: mock proxy server in future
_, err := client.R().SetResult(&json).Get(ts.URL + "/get")
if err != nil {
t.Fatal(err)
}else {
t.Logf("response json:%#v\n", json)
}
}
2 changes: 1 addition & 1 deletion examples/req_header_test.go
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/go-resty/resty/v3"
)

// Send headers
// Example about sending headers
func TestSendHeader(t *testing.T) {
ts := createHttpbinServer(0)
defer ts.Close()
Expand Down
1 change: 1 addition & 0 deletions examples/response_build_test.go
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/go-resty/resty/v3"
)

// Example about building response
func TestResponseBuilder(t *testing.T) {
var err error
var data = 1
Expand Down

0 comments on commit 606416e

Please sign in to comment.