GoRequest

repository·develop·Indexed 25 days ago

https://github.com/parnurzeal/gorequest

A simplified HTTP client for Go inspired by the Node.js SuperAgent library. It provides a fluent, chainable API for sending complex requests, including support for JSON, multipart/form-data, file uploads, and Basic Auth. Key features include automatic JSON marshaling, custom redirect policies, request retries, and debugging tools such as generating equivalent CURL commands.

Tokens
3.1K
Snippets
10
Records
29
Agent score
36%

What's inside gorequest

  1. Perform basic HTTP requests with GoRequest

    develop

    GoRequest provides a simplified interface for common HTTP methods. You can create a new request instance using gorequest.New() and chain method calls like Get, Post, Put, Delete, Head, or Patch. Use .End() to execute the request and receive the response, body, and errors.

    request := gorequest.New()
    resp, body, errs := request.Get("http://example.com/").End()
    
    // Or in a single line:
    resp, body, errs := gorequest.New().Get("http://example.com/").End()
  2. Send multipart/form-data and files

    develop

    To send multipart requests, use .Type("multipart"). You can send files using .SendFile(), which accepts a file path (string), a []byte slice, or an os.File. You can also specify a custom field name for the file.

    // Sending a simple multipart request
    gorequest.New().Post("http://example.com/").
      Type("multipart").
      Send(`{"query1":"test"}`).
      End()
    
    // Sending multiple files
    // file2.txt is sent with custom field name 'my_file_fieldname'
    gorequest.New().Post("http://example.com/").
      Type("multipart").
      SendFile("./file1.txt").
      SendFile(bytesOfFile, "file2.txt", "my_file_fieldname").
      End()
  3. Send JSON data in requests

    develop

    To send JSON data, use the .Send() method. GoRequest automatically handles JSON marshaling for both JSON strings and Go structs. You can chain multiple .Send() calls to mix and match different data types.

    // Sending a JSON string
    request := gorequest.New()
    resp, body, errs := request.Post("http://example.com/").
      Set("Notes","gorequst is coming!").
      Send(`{"name":"backy", "species":"dog"}`).
      End()
    
    // Sending a struct
    type BrowserVersionSupport struct {
      Chrome string
      Firefox string
    }
    ver := BrowserVersionSupport{ Chrome: "37.0.2041.6", Firefox: "30.0" }
    resp, body, errs := gorequest.New().Post("http://version.com/update").
      Send(ver).
      Send(`{"Safari":"5.1.10"}`).
      End()
  4. Use callbacks for request handling

    develop

    Instead of capturing return values from .End(), you can pass a callback function to .End(callback). The callback receives the gorequest.Response, the response body as a string, and a slice of errors.

    func printStatus(resp gorequest.Response, body string, errs []error){
      fmt.Println(resp.Status)
    }
    gorequest.New().Get("http://example.com").End(printStatus)
  5. Handle redirects with RedirectPolicy

    develop

    Customize redirect behavior using .RedirectPolicy(func). The function signature matches net/http's CheckRedirect: it takes the current Request and a slice of previous []*Request. Returning http.ErrUseLastResponse stops the redirect and returns the last response.

    request := gorequest.New()
    resp, body, errs := request.Get("http://example.com/").
                        RedirectPolicy(func(req Request, via []*Request) error {
                          if req.URL.Scheme != "https" {
                            return http.ErrUseLastResponse
                          }
                          return nil
                        }).
                        End()
  6. Retry failed requests

    develop

    Use .Retry(attempts, interval, ...errorCodes) to automatically retry a request. The interval is a time.Duration between attempts, and you can specify which HTTP status codes should trigger a retry.

    request := gorequest.New()
    resp, body, errs := request.Get("http://example.com/").
                        Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError).
                        End()
  7. Enable Debug mode

    develop
    To debug requests and responses, you can use .SetDebug(true) or set the environment variable GOREQUEST_DEBUG=1. You can also use .SetLogger(logger) to provide a custom logger. Additionally, .SetCurlCommand() can be used to see the equivalent CURL command.
  8. Parse response body as Bytes or Structs

    develop

    Instead of .End(), use these methods to get the response in specific formats:

    • .EndBytes(): Returns the body as a []byte.
    • .EndStruct(target): Unmarshals the JSON response body into the provided pointer target.
  9. Clone a request for reuse

    develop
    Use .Clone() to create a shallow copy of a request's settings (headers, query, etc.) without sharing the same request state. Clones share the same underlying Transport and http.Client, making them efficient for multiple requests with the same base configuration.