req

package module
v3.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2022 License: MIT Imports: 49 Imported by: 561

README

Req

Simplified Golang HTTP client library with Black Magic, Less code and More efficiency.

News

Brand-New version v3 is released, which is completely rewritten, bringing revolutionary innovations and many superpowers, try and enjoy :)

If you want to use the older version, check it out on v1 branch.

v2 is a transitional version, due to some breaking changes were introduced during optmize user experience

Table of Contents

Features

  • Simple and chainable methods for both client-level and request-level settings, and the request-level setting takes precedence if both are set.
  • Powerful and convenient debug utilites, including debug logs, performance traces, and even dump the complete request and response content (see Debugging - Dump/Log/Trace.
  • Easy making HTTP test with code instead of tools like curl or postman, req provide global wrapper methods and MustXXX to test API with minimal code (see Quick HTTP Test).
  • Works fine with both HTTP/2 and HTTP/1.1, which HTTP/2 is preferred by default if server support, and you can also force HTTP/1.1 if you want (see HTTP2 and HTTP1).
  • Detect the charset of response body and decode it to utf-8 automatically to avoid garbled characters by default (see Auto-Decode).
  • Automatic marshal and unmarshal for JSON and XML content type and fully customizable (see Body and Marshal/Unmarshal).
  • Exportable Transport, easy to integrate with existing http.Client, debug APIs with minimal code change.
  • Easy Download and Upload.
  • Easy set header, cookie, path parameter, query parameter, form data, basic auth, bearer token for both client and request level.
  • Easy set timeout, proxy, certs, redirect policy, cookie jar, compression, keepalives etc for client.
  • Support middleware before request sent and after got response (see Request and Response Middleware).

Quick Start

Install

go get github.com/imroc/req/v3

Import

import "github.com/imroc/req/v3"
// For test, you can create and send a request with the global default
// client, use DevMode to see all details, try and suprise :)
req.DevMode()
req.Get("https://api.github.com/users/imroc")

// Create and send a request with the custom client and settings
client := req.C(). // Use C() to create a client
    SetUserAgent("my-custom-client"). // Chainable client settings
    SetTimeout(5 * time.Second).
    DevMode()
resp, err := client.R(). // Use R() to create a request
    SetHeader("Accept", "application/vnd.github.v3+json"). // Chainable request settings
    SetPathParam("username", "imroc").
    SetQueryParam("page", "1").
    SetResult(&result).
    Get("https://api.github.com/users/{username}/repos")

Checkout more runnable examples in the examples direcotry.

API Reference

Checkout Req API Reference for a brief and categorized list of the core APIs, for a more detailed and complete list of APIs, please refer to GoDoc.

Debugging - Dump/Log/Trace

Dump the Content

// Enable dump at client level, which will dump for all requests,
// including all content of request and response and output
// to stdout by default.
client := req.C().EnableDumpAll()
client.R().Get("https://httpbin.org/get")

/* Output
:authority: httpbin.org
:method: GET
:path: /get
:scheme: https
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
accept-encoding: gzip

:status: 200
date: Wed, 26 Jan 2022 06:39:20 GMT
content-type: application/json
content-length: 372
server: gunicorn/19.9.0
access-control-allow-origin: *
access-control-allow-credentials: true

{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
    "X-Amzn-Trace-Id": "Root=1-61f0ec98-5958c02662de26e458b7672b"
  },
  "origin": "103.7.29.30",
  "url": "https://httpbin.org/get"
}
*/
	
// Customize dump settings with predefined and convenient settings at client level. 
client.EnableDumpAllWithoutBody(). // Only dump the header of request and response
    EnableDumpAllAsync(). // Dump asynchronously to improve performance
    EnableDumpAllToFile("reqdump.log") // Dump to file without printing it out
// Send request to see the content that have been dumped	
client.R().Get(url) 

// Enable dump with fully customized settings at client level.
opt := &req.DumpOptions{
            Output:         os.Stdout,
            RequestHeader:  true,
            ResponseBody:   true,
            RequestBody:    false,
            ResponseHeader: false,
            Async:          false,
        }
client.SetCommonDumpOptions(opt).EnableDumpAll()
client.R().Get("https://httpbin.org/get")

// Change settings dynamiclly
opt.ResponseBody = false
client.R().Get("https://httpbin.org/get")

// You can also enable dump at request level, which will not override client-level dumping,
// dump to the internal buffer and will not print it out by default, you can call `Response.Dump()`
// to get the dump result and print only if you want to, typically used in production, only record
// the content of the request when the request is abnormal to help us troubleshoot problems.
resp, err := client.R().EnableDump().SetBody("test body").Post("https://httpbin.org/post")
if err != nil {
    fmt.Println("err:", err)
	if resp.Dump() != "" {
        fmt.Println("raw content:")
        fmt.Println(resp.Dump())
    }
    return
}
if !resp.IsSuccess() { // Status code not beetween 200 and 299
    fmt.Println("bad status:", resp.Status)
    fmt.Println("raw content:")
    fmt.Println(resp.Dump())
    return
}

// Similarly, also support to customize dump settings with the predefined and convenient settings at request level.
resp, err = client.R().EnableDumpWithoutRequest().SetBody("test body").Post("https://httpbin.org/post")
// ...
resp, err = client.R().SetDumpOptions(opt).EnableDump().SetBody("test body").Post("https://httpbin.org/post")

Enable DebugLog for Deeper Insights

// Logging is enabled by default, but only output the warning and error message.
// Use `EnableDebugLog` to enable debug level logging.
client := req.C().EnableDebugLog()
client.R().Get("http://baidu.com/s?wd=req")
/* Output
2022/01/26 15:46:29.279368 DEBUG [req] GET http://baidu.com/s?wd=req
2022/01/26 15:46:29.469653 DEBUG [req] charset iso-8859-1 detected in Content-Type, auto-decode to utf-8
2022/01/26 15:46:29.469713 DEBUG [req] <redirect> GET http://www.baidu.com/s?wd=req
...
*/

// SetLogger with nil to disable all log
client.SetLogger(nil)

// Or customize the logger with your own implementation.
client.SetLogger(logger)

Enable Trace to Analyze Performance

// Enable trace at request level
client := req.C()
resp, err := client.R().EnableTrace().Get("https://api.github.com/users/imroc")
if err != nil {
	log.Fatal(err)
}
trace := resp.TraceInfo() // Use `resp.Request.TraceInfo()` to avoid unnecessary struct copy in production.
fmt.Println(trace.Blame()) // Print out exactly where the http request is slowing down.
fmt.Println("----------")
fmt.Println(trace) // Print details

/* Output
the request total time is 2.562416041s, and costs 1.289082208s from connection ready to server respond frist byte
--------
TotalTime         : 2.562416041s
DNSLookupTime     : 445.246375ms
TCPConnectTime    : 428.458µs
TLSHandshakeTime  : 825.888208ms
FirstResponseTime : 1.289082208s
ResponseTime      : 1.712375ms
IsConnReused:     : false
RemoteAddr        : 98.126.155.187:443
*/

// Enable trace at client level
client.EnableTraceAll()
resp, err = client.R().Get(url)
// ...

DevMode

If you want to enable all debug features (dump, debug log and tracing), just call DevMode():

client := req.C().DevMode()
client.R().Get("https://imroc.cc")

Quick HTTP Test

Test with Global Wrapper Methods

req wrap methods of both Client and Request with global methods, which is delegated to the default client behind the scenes, so you can just treat the package name req as a Client or Request to test quickly without create one explicitly.

// Call the global methods just like the Client's method,
// so you can treat package name `req` as a Client, and
// you don't need to create any client explicitly.
req.SetTimeout(5 * time.Second).
	SetCommonBasicAuth("imroc", "123456").
	SetCommonHeader("Accept", "text/xml").
	SetUserAgent("my api client").
	DevMode()

// Call the global method just like the Request's method,
// which will create request automatically using the default
// client, so you can treat package name `req` as a Request,
// and you don't need to create any request and client explicitly.
req.SetQueryParam("page", "2").
	SetHeader("Accept", "application/json"). // Override client level settings at request level.
	Get("https://httpbin.org/get")

Test with MustXXX

Use MustXXX to ignore error handling during test, make it possible to complete a complex test with just one line of code:

fmt.Println(req.DevMode().R().MustGet("https://imroc.cc").TraceInfo())

HTTP2 and HTTP1

Req works fine both with HTTP/2 and HTTP/1.1, HTTP/2 is preferred by default if server support, which is negotiated by TLS handshake.

You can force using HTTP/1.1 if you want.

client := req.C().EnableForceHTTP1().EnableDumpAllWithoutBody()
client.R().MustGet("https://httpbin.org/get")
/* Output
GET /get HTTP/1.1
Host: httpbin.org
User-Agent: req/v3 (https://github.com/imroc/req)
Accept-Encoding: gzip

HTTP/1.1 200 OK
Date: Tue, 08 Feb 2022 02:30:18 GMT
Content-Type: application/json
Content-Length: 289
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
*/

And also you can force using HTTP/2 if you want, will return error if server does not support:

client := req.C().EnableForceHTTP2()
client.R().MustGet("https://baidu.com")
/* Output
panic: Get "https://baidu.com": server does not support http2, you can use http/1.1 which is supported
*/

URL Path and Query Parameter

Path Parameter

Use SetPathParam or SetPathParams to replace variable in the url path:

client := req.C().DevMode()

client.R().
    SetPathParam("owner", "imroc"). // Set a path param, which will replace the vairable in url path
    SetPathParams(map[string]string{ // Set multiple path params at once 
        "repo": "req",
        "path": "README.md",
    }).Get("https://api.github.com/repos/{owner}/{repo}/contents/{path}") // path parameter will replace path variable in the url
/* Output
2022/01/23 14:43:59.114592 DEBUG [req] GET https://api.github.com/repos/imroc/req/contents/README.md
...
*/

// You can also set the common PathParam for every request on client
client.SetCommonPathParam(k1, v1).SetCommonPathParams(pathParams)
	
resp1, err := client.Get(url1)
...

resp2, err := client.Get(url2)
...

Query Parameter

Use SetQueryParam, SetQueryParams or SetQueryString to append url query parameter:

client := req.C().DevMode()

// Set query parameter at request level.
client.R().
    SetQueryParam("a", "a"). // Set a query param, which will be encoded as query parameter in url
    SetQueryParams(map[string]string{ // Set multiple query params at once 
        "b": "b",
        "c": "c",
    }).SetQueryString("d=d&e=e"). // Set query params as a raw query string
    Get("https://api.github.com/repos/imroc/req/contents/README.md?x=x")
/* Output
2022/01/23 14:43:59.114592 DEBUG [req] GET https://api.github.com/repos/imroc/req/contents/README.md?x=x&a=a&b=b&c=c&d=d&e=e
...
*/

// You can also set the query parameter at client level.
client.SetCommonQueryParam(k, v).
    SetCommonQueryParams(queryParams).
    SetCommonQueryString(queryString).
	
resp1, err := client.Get(url1)
...
resp2, err := client.Get(url2)
...

// Add query parameter with multiple values at request level.
client.R().AddQueryParam("key", "value1").AddQueryParam("key", "value2").Get("https://httpbin.org/get")
/* Output
2022/02/05 08:49:26.260780 DEBUG [req] GET https://httpbin.org/get?key=value1&key=value2
...
 */


// Multiple values also supported at client level.
client.AddCommonQueryParam("key", "value1").AddCommonQueryParam("key", "value2")

Form Data

client := req.C().EnableDumpAllWithoutResponse()
client.R().SetFormData(map[string]string{
    "username": "imroc",
    "blog":     "https://imroc.cc",
}).Post("https://httpbin.org/post")
/* Output
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
content-type: application/x-www-form-urlencoded
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

blog=https%3A%2F%2Fimroc.cc&username=imroc
*/

// Multi value form data
v := url.Values{
    "multi": []string{"a", "b", "c"},
}
client.R().SetFormDataFromValues(v).Post("https://httpbin.org/post")
/* Output
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
content-type: application/x-www-form-urlencoded
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

multi=a&multi=b&multi=c
*/

// You can also set form data in client level
client.SetCommonFormData(m)
client.SetCommonFormDataFromValues(v)

GET, HEAD, and OPTIONS requests ignores form data by default

Set Header

// Let's dump the header to see what's going on
client := req.C().EnableForceHTTP1().EnableDumpAllWithoutResponse() 

// Send a request with multiple headers and cookies
client.R().
    SetHeader("Accept", "application/json"). // Set one header
    SetHeaders(map[string]string{ // Set multiple headers at once 
        "My-Custom-Header": "My Custom Value",
        "User":             "imroc",
    }).Get("https://httpbin.org/get")

/* Output
GET /get HTTP/1.1
Host: httpbin.org
User-Agent: req/v3 (https://github.com/imroc/req)
Accept: application/json
My-Custom-Header: My Custom Value
User: imroc
Accept-Encoding: gzip
*/

// You can also set the common header and cookie for every request on client.
client.SetCommonHeader(header).SetCommonHeaders(headers)

resp1, err := client.R().Get(url1)
...
resp2, err := client.R().Get(url2)
...

Set Cookie

// Let's dump the header to see what's going on
client := req.C().EnableForceHTTP1().EnableDumpAllWithoutResponse() 

// Send a request with multiple headers and cookies
client.R().
    SetCookies(
		&http.Cookie{
            Name:     "testcookie1",
            Value:    "testcookie1 value",
            Path:     "/",
            Domain:   "baidu.com",
            MaxAge:   36000,
            HttpOnly: false,
            Secure:   true,
        },
        &http.Cookie{
            Name:     "testcookie2",
            Value:    "testcookie2 value",
            Path:     "/",
            Domain:   "baidu.com",
            MaxAge:   36000,
            HttpOnly: false,
            Secure:   true,
        },
    ).Get("https://httpbin.org/get")

/* Output
GET /get HTTP/1.1
Host: httpbin.org
User-Agent: req/v3 (https://github.com/imroc/req)
Cookie: testcookie1="testcookie1 value"; testcookie2="testcookie2 value"
Accept-Encoding: gzip
*/

// You can also set the common cookie for every request on client.
client.SetCommonCookies(cookie1, cookie2, cookie3)

resp1, err := client.R().Get(url1)
...
resp2, err := client.R().Get(url2)

You can also customize the CookieJar:

// Set your own http.CookieJar implementation
client.SetCookieJar(jar)

// Set to nil to disable CookieJar
client.SetCookieJar(nil)

Body and Marshal/Unmarshal

Request Body

// Create a client that dump request
client := req.C().EnableDumpAllWithoutResponse()
// SetBody accepts string, []byte, io.Reader, use type assertion to
// determine the data type of body automatically. 
client.R().SetBody("test").Post("https://httpbin.org/post")
/* Output
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

test
*/

// If it cannot determine, like map and struct, then it will wait
// and marshal to JSON or XML automatically according to the `Content-Type`
// header that have been set before or after, default to json if not set.
type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
user := &User{Name: "imroc", Email: "roc@imroc.cc"}
client.R().SetBody(user).Post("https://httpbin.org/post")
/* Output
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
content-type: application/json; charset=utf-8
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

{"name":"imroc","email":"roc@imroc.cc"}
*/


// You can use more specific methods to avoid type assertions and improves performance,
client.R().SetBodyJsonString(`{"username": "imroc"}`).Post("https://httpbin.org/post")
/*
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
content-type: application/json; charset=utf-8
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

{"username": "imroc"}
*/

// Marshal body and set `Content-Type` automatically without any guess
cient.R().SetBodyXmlMarshal(user).Post("https://httpbin.org/post")
/* Output
:authority: httpbin.org
:method: POST
:path: /post
:scheme: https
content-type: text/xml; charset=utf-8
accept-encoding: gzip
user-agent: req/v2 (https://github.com/imroc/req)

<User><Name>imroc</Name><Email>roc@imroc.cc</Email></User>
*/

Response Body

// Define success body struct
type User struct {
    Name string `json:"name"`
    Blog string `json:"blog"`
}
// Define error body struct
type ErrorMessage struct {
    Message string `json:"message"`
}
// Create a client and dump body to see details
client := req.C().EnableDumpAllWithoutHeader()

// Send a request and unmarshal result automatically according to
// response `Content-Type`
user := &User{}
errMsg := &ErrorMessage{}
resp, err := client.R().
	SetResult(user). // Set success result
	SetError(errMsg). // Set error result
	Get("https://api.github.com/users/imroc")
if err != nil {
    log.Fatal(err)
}
fmt.Println("----------")

if resp.IsSuccess() { // status `code >= 200 and <= 299` is considered as success
	// Must have been marshaled to user if no error returned before
    fmt.Printf("%s's blog is %s\n", user.Name, user.Blog)
} else if resp.IsError() { // status `code >= 400` is considered as error
	// Must have been marshaled to errMsg if no error returned before
    fmt.Println("got error:", errMsg.Message) 
} else {
    log.Fatal("unknown http status:", resp.Status)
}
/* Output
{"login":"imroc","id":7448852,"node_id":"MDQ6VXNlcjc0NDg4NTI=","avatar_url":"https://avatars.githubusercontent.com/u/7448852?v=4","gravatar_id":"","url":"https://api.github.com/users/imroc","html_url":"https://github.com/imroc","followers_url":"https://api.github.com/users/imroc/followers","following_url":"https://api.github.com/users/imroc/following{/other_user}","gists_url":"https://api.github.com/users/imroc/gists{/gist_id}","starred_url":"https://api.github.com/users/imroc/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/imroc/subscriptions","organizations_url":"https://api.github.com/users/imroc/orgs","repos_url":"https://api.github.com/users/imroc/repos","events_url":"https://api.github.com/users/imroc/events{/privacy}","received_events_url":"https://api.github.com/users/imroc/received_events","type":"User","site_admin":false,"name":"roc","company":"Tencent","blog":"https://imroc.cc","location":"China","email":null,"hireable":true,"bio":"I'm roc","twitter_username":"imrocchan","public_repos":129,"public_gists":0,"followers":362,"following":151,"created_at":"2014-04-30T10:50:46Z","updated_at":"2022-01-24T23:32:53Z"}
----------
roc's blog is https://imroc.cc
*/

// Or you can also unmarshal response later
if resp.IsSuccess() {
    err = resp.Unmarshal(user)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s's blog is %s\n", user.Name, user.Blog)
} else {
    fmt.Println("bad response:", resp)
}

// Also, you can get the raw response and Unmarshal by yourself
yaml.Unmarshal(resp.Bytes())

Customize JSON&XML Marshal/Unmarshal

// Example of registering json-iterator
import jsoniter "github.com/json-iterator/go"

json := jsoniter.ConfigCompatibleWithStandardLibrary

client := req.C().
	SetJsonMarshal(json.Marshal).
	SetJsonUnmarshal(json.Unmarshal)

// Similarly, XML functions can also be customized
client.SetXmlMarshal(xmlMarshalFunc).SetXmlUnmarshal(xmlUnmarshalFunc)

Disable Auto-Read Response Body

Response body will be read into memory if it's not a download request by default, you can disable it if you want (normally you don't need to do this).

client.DisableAutoReadResponse()

resp, err := client.R().Get(url)
if err != nil {
	log.Fatal(err)
}
io.Copy(dst, resp.Body)

Custom Certificates

client := req.R()

// Set root cert and client cert from file path
client.SetRootCertsFromFile("/path/to/root/certs/pemFile1.pem", "/path/to/root/certs/pemFile2.pem", "/path/to/root/certs/pemFile3.pem"). // Set root cert from one or more pem files
    SetCertFromFile("/path/to/client/certs/client.pem", "/path/to/client/certs/client.key") // Set client cert and key cert file
	
// You can also set root cert from string
client.SetRootCertFromString("-----BEGIN CERTIFICATE-----XXXXXX-----END CERTIFICATE-----")

// And set client cert with 
cert1, err := tls.LoadX509KeyPair("/path/to/client/certs/client.pem", "/path/to/client/certs/client.key")
if err != nil {
    log.Fatalf("ERROR client certificate: %s", err)
}
// ...

// you can add more certs if you want
client.SetCerts(cert1, cert2, cert3) 

Basic Auth and Bearer Token

client := req.C()

// Set basic auth for all request
client.SetCommonBasicAuth("imroc", "123456")

// Set bearer token for all request
client.SetCommonBearerAuthToken("MDc0ZTg5YmU4Yzc5MjAzZGJjM2ZiMzkz")

// Set basic auth for a request, will override client's basic auth setting.
client.R().SetBasicAuth("myusername", "mypassword").Get("https://api.example.com/profile")

// Set bearer token for a request, will override client's bearer token setting.
client.R().SetBearerToken("NGU1ZWYwZDJhNmZhZmJhODhmMjQ3ZDc4").Get("https://api.example.com/profile")

Download and Upload

Download

// Create a client with default download direcotry
client := req.C().SetOutputDirectory("/path/to/download").EnableDumpNoResponseBody()

// Download to relative file path, this will be downloaded
// to /path/to/download/test.jpg
client.R().SetOutputFile("test.jpg").Get(url)

// Download to absolute file path, ignore the output directory
// setting from Client
client.R().SetOutputFile("/tmp/test.jpg").Get(url)

// You can also save file to any `io.WriteCloser`
file, err := os.Create("/tmp/test.jpg")
if err != nil {
	fmt.Println(err)
	return
}
client.R().SetOutput(file).Get(url)

Multipart Upload

client := req.().EnableDumpNoRequestBody() // Request body contains unreadable binary, do not dump

client.R().SetFile("pic", "test.jpg"). // Set form param name and filename
    SetFile("pic", "/path/to/roc.png"). // Multiple files using the same form param name
    SetFiles(map[string]string{ // Set multiple files using map
        "exe": "test.exe",
        "src": "main.go",
    }).
    SetFormData(map[string]string{ // Set from param using map
        "name":  "imroc",
        "email": "roc@imroc.cc",
    }).
	SetFromDataFromValues(values). // You can also set form data using `url.Values`
    Post("http://127.0.0.1:8888/upload")

// You can also use io.Reader to upload
avatarImgFile, _ := os.Open("avatar.png")
client.R().SetFileReader("avatar", "avatar.png", avatarImgFile).Post(url)
*/

Auto-Decode

Req detect the charset of response body and decode it to utf-8 automatically to avoid garbled characters by default.

Its principle is to detect Content-Type header at first, if it's not the text content type (json, xml, html and so on), req will not try to decode. If it is, then req will try to find the charset information. And req also will try to sniff the body's content to determine the charset if the charset information is not included in the header, if sniffed out and not utf-8, then decode it to utf-8 automatically, and req will not try to decode if the charset is not sure, just leave the body untouched.

You can also disable it if you don't need or care a lot about performance:

client.DisableAutoDecode()

And also you can make some customization:

// Try to auto-detect and decode all content types (some server may return incorrect Content-Type header)
client.SetAutoDecodeAllContentType()

// Only auto-detect and decode content which `Content-Type` header contains "html" or "json"
client.SetAutoDecodeContentType("html", "json")

// Or you can customize the function to determine whether to decode
fn := func(contentType string) bool {
    if regexContentType.MatchString(contentType) {
        return true
    }
    return false
}
client.SetAutoDecodeContentTypeFunc(fn)

Request and Response Middleware

client := req.C()

// Registering Request Middleware
client.OnBeforeRequest(func(c *req.Client, r *req.Request) error {
	// You can access Client and current Request object to do something
	// as you need

    return nil  // return nil if it is success
  })

// Registering Response Middleware
client.OnAfterResponse(func(c *req.Client, r *req.Response) error {
    // You can access Client and current Response object to do something
    // as you need

    return nil  // return nil if it is success
  })

Redirect Policy

client := req.C().EnableDumpAllWithoutResponse()

client.SetRedirectPolicy(
    // Only allow up to 5 redirects
    req.MaxRedirectPolicy(5),
    // Only allow redirect to same domain.
    // e.g. redirect "www.imroc.cc" to "imroc.cc" is allowed, but "google.com" is not
    req.SameDomainRedirectPolicy(),
)

client.SetRedirectPolicy(
    // Only *.google.com/google.com and *.imroc.cc/imroc.cc is allowed to redirect
    req.AllowedDomainRedirectPolicy("google.com", "imroc.cc"),
    // Only allow redirect to same host.
    // e.g. redirect "www.imroc.cc" to "imroc.cc" is not allowed, only "www.imroc.cc" is allowed
    req.SameHostRedirectPolicy(),
)

// All redirect is not allowd
client.SetRedirectPolicy(req.NoRedirectPolicy())

// Or customize the redirect with your own implementation
client.SetRedirectPolicy(func(req *http.Request, via []*http.Request) error {
    // ...
})

Proxy

Req use proxy http.ProxyFromEnvironment by default, which will read the HTTP_PROXY/HTTPS_PROXY/http_proxy/https_proxy environment variable, and setup proxy if environment variable is been set. You can customize it if you need:

// Set proxy from proxy url
client.SetProxyURL("http://myproxy:8080")

// Custmize the proxy function with your own implementation
client.SetProxy(func(request *http.Request) (*url.URL, error) {
    // ...
})

// Disable proxy
client.SetProxy(nil)

TODO List

  • Add more tests.
  • Wrap more transport settings into client.
  • Support retry.
  • Support unix socket.
  • Support h2c.
  • Support HTTP3.

License

Req released under MIT license, refer LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoBody = noBody{}

NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set Request.Body to nil.

Functions

func CanonicalMIMEHeaderKey

func CanonicalMIMEHeaderKey(s string) string

CanonicalMIMEHeaderKey returns the canonical format of the MIME header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". MIME header keys are assumed to be ASCII only. If s contains a space or invalid header field bytes, it is returned without modifications.

func GetTLSClientConfig added in v3.6.0

func GetTLSClientConfig() *tls.Config

GetTLSClientConfig is a global wrapper methods which delegated to the default client's GetTLSClientConfig.

func SetDefaultClient

func SetDefaultClient(c *Client)

SetDefaultClient override the global default Client.

Types

type Client

type Client struct {
	BaseURL               string
	PathParams            map[string]string
	QueryParams           urlpkg.Values
	Headers               http.Header
	Cookies               []*http.Cookie
	FormData              urlpkg.Values
	DebugLog              bool
	AllowGetMethodPayload bool
	// contains filtered or unexported fields
}

Client is the req's http client.

func AddCommonQueryParam

func AddCommonQueryParam(key, value string) *Client

AddCommonQueryParam is a global wrapper methods which delegated to the default client's AddCommonQueryParam.

func C

func C() *Client

C create a new client.

func DefaultClient

func DefaultClient() *Client

DefaultClient returns the global default Client.

func DevMode

func DevMode() *Client

DevMode is a global wrapper methods which delegated to the default client's DevMode.

func DisableAllowGetMethodPayload

func DisableAllowGetMethodPayload() *Client

DisableAllowGetMethodPayload is a global wrapper methods which delegated to the default client's DisableAllowGetMethodPayload.

func DisableAutoDecode

func DisableAutoDecode() *Client

DisableAutoDecode is a global wrapper methods which delegated to the default client's DisableAutoDecode.

func DisableAutoReadResponse

func DisableAutoReadResponse() *Client

DisableAutoReadResponse is a global wrapper methods which delegated to the default client's DisableAutoReadResponse.

func DisableCompression

func DisableCompression() *Client

DisableCompression is a global wrapper methods which delegated to the default client's DisableCompression.

func DisableDebugLog

func DisableDebugLog() *Client

DisableDebugLog is a global wrapper methods which delegated to the default client's DisableDebugLog.

func DisableDumpAll

func DisableDumpAll() *Client

DisableDumpAll is a global wrapper methods which delegated to the default client's DisableDumpAll.

func DisableForceHttpVersion added in v3.4.0

func DisableForceHttpVersion() *Client

DisableForceHttpVersion is a global wrapper methods which delegated to the default client's DisableForceHttpVersion.

func DisableInsecureSkipVerify added in v3.6.0

func DisableInsecureSkipVerify() *Client

DisableInsecureSkipVerify is a global wrapper methods which delegated to the default client's DisableInsecureSkipVerify.

func DisableKeepAlives

func DisableKeepAlives() *Client

DisableKeepAlives is a global wrapper methods which delegated to the default client's DisableKeepAlives.

func DisableTraceAll

func DisableTraceAll() *Client

DisableTraceAll is a global wrapper methods which delegated to the default client's DisableTraceAll.

func EnableAllowGetMethodPayload

func EnableAllowGetMethodPayload() *Client

EnableAllowGetMethodPayload is a global wrapper methods which delegated to the default client's EnableAllowGetMethodPayload.

func EnableAutoDecode

func EnableAutoDecode() *Client

EnableAutoDecode is a global wrapper methods which delegated to the default client's EnableAutoDecode.

func EnableAutoReadResponse

func EnableAutoReadResponse() *Client

EnableAutoReadResponse is a global wrapper methods which delegated to the default client's EnableAutoReadResponse.

func EnableCompression

func EnableCompression() *Client

EnableCompression is a global wrapper methods which delegated to the default client's EnableCompression.

func EnableDebugLog

func EnableDebugLog() *Client

EnableDebugLog is a global wrapper methods which delegated to the default client's EnableDebugLog.

func EnableDumpAll

func EnableDumpAll() *Client

EnableDumpAll is a global wrapper methods which delegated to the default client's EnableDumpAll.

func EnableDumpAllAsync

func EnableDumpAllAsync() *Client

EnableDumpAllAsync is a global wrapper methods which delegated to the default client's EnableDumpAllAsync.

func EnableDumpAllTo

func EnableDumpAllTo(output io.Writer) *Client

EnableDumpAllTo is a global wrapper methods which delegated to the default client's EnableDumpAllTo.

func EnableDumpAllToFile

func EnableDumpAllToFile(filename string) *Client

EnableDumpAllToFile is a global wrapper methods which delegated to the default client's EnableDumpAllToFile.

func EnableDumpAllWithoutBody

func EnableDumpAllWithoutBody() *Client

EnableDumpAllWithoutBody is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutBody.

func EnableDumpAllWithoutHeader

func EnableDumpAllWithoutHeader() *Client

EnableDumpAllWithoutHeader is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutHeader.

func EnableDumpAllWithoutRequest added in v3.1.0

func EnableDumpAllWithoutRequest() *Client

EnableDumpAllWithoutRequest is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutRequest.

func EnableDumpAllWithoutRequestBody

func EnableDumpAllWithoutRequestBody() *Client

EnableDumpAllWithoutRequestBody is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutRequestBody.

func EnableDumpAllWithoutResponse

func EnableDumpAllWithoutResponse() *Client

EnableDumpAllWithoutResponse is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutResponse.

func EnableDumpAllWithoutResponseBody

func EnableDumpAllWithoutResponseBody() *Client

EnableDumpAllWithoutResponseBody is a global wrapper methods which delegated to the default client's EnableDumpAllWithoutResponseBody.

func EnableForceHTTP1 added in v3.2.0

func EnableForceHTTP1() *Client

EnableForceHTTP1 is a global wrapper methods which delegated to the default client's EnableForceHTTP1.

func EnableForceHTTP2 added in v3.4.0

func EnableForceHTTP2() *Client

EnableForceHTTP2 is a global wrapper methods which delegated to the default client's EnableForceHTTP2.

func EnableInsecureSkipVerify added in v3.6.0

func EnableInsecureSkipVerify() *Client

EnableInsecureSkipVerify is a global wrapper methods which delegated to the default client's EnableInsecureSkipVerify.

func EnableKeepAlives

func EnableKeepAlives() *Client

EnableKeepAlives is a global wrapper methods which delegated to the default client's EnableKeepAlives.

func EnableTraceAll

func EnableTraceAll() *Client

EnableTraceAll is a global wrapper methods which delegated to the default client's EnableTraceAll.

func NewClient

func NewClient() *Client

NewClient is the alias of C

func OnAfterResponse

func OnAfterResponse(m ResponseMiddleware) *Client

OnAfterResponse is a global wrapper methods which delegated to the default client's OnAfterResponse.

func OnBeforeRequest

func OnBeforeRequest(m RequestMiddleware) *Client

OnBeforeRequest is a global wrapper methods which delegated to the default client's OnBeforeRequest.

func SetAutoDecodeAllContentType added in v3.3.0

func SetAutoDecodeAllContentType() *Client

SetAutoDecodeAllContentType is a global wrapper methods which delegated to the default client's SetAutoDecodeAllContentType.

func SetAutoDecodeContentType

func SetAutoDecodeContentType(contentTypes ...string) *Client

SetAutoDecodeContentType is a global wrapper methods which delegated to the default client's SetAutoDecodeContentType.

func SetAutoDecodeContentTypeFunc added in v3.3.0

func SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client

SetAutoDecodeContentTypeFunc is a global wrapper methods which delegated to the default client's SetAutoDecodeAllTypeFunc.

func SetBaseURL

func SetBaseURL(u string) *Client

SetBaseURL is a global wrapper methods which delegated to the default client's SetBaseURL.

func SetCertFromFile

func SetCertFromFile(certFile, keyFile string) *Client

SetCertFromFile is a global wrapper methods which delegated to the default client's SetCertFromFile.

func SetCerts

func SetCerts(certs ...tls.Certificate) *Client

SetCerts is a global wrapper methods which delegated to the default client's SetCerts.

func SetCommonBasicAuth

func SetCommonBasicAuth(username, password string) *Client

SetCommonBasicAuth is a global wrapper methods which delegated to the default client's SetCommonBasicAuth.

func SetCommonBearerAuthToken

func SetCommonBearerAuthToken(token string) *Client

SetCommonBearerAuthToken is a global wrapper methods which delegated to the default client's SetCommonBearerAuthToken.

func SetCommonContentType

func SetCommonContentType(ct string) *Client

SetCommonContentType is a global wrapper methods which delegated to the default client's SetCommonContentType.

func SetCommonCookies

func SetCommonCookies(cookies ...*http.Cookie) *Client

SetCommonCookies is a global wrapper methods which delegated to the default client's SetCommonCookies.

func SetCommonDumpOptions

func SetCommonDumpOptions(opt *DumpOptions) *Client

SetCommonDumpOptions is a global wrapper methods which delegated to the default client's SetCommonDumpOptions.

func SetCommonFormData

func SetCommonFormData(data map[string]string) *Client

SetCommonFormData is a global wrapper methods which delegated to the default client's SetCommonFormData.

func SetCommonFormDataFromValues

func SetCommonFormDataFromValues(data urlpkg.Values) *Client

SetCommonFormDataFromValues is a global wrapper methods which delegated to the default client's SetCommonFormDataFromValues.

func SetCommonHeader

func SetCommonHeader(key, value string) *Client

SetCommonHeader is a global wrapper methods which delegated to the default client's SetCommonHeader.

func SetCommonHeaders

func SetCommonHeaders(hdrs map[string]string) *Client

SetCommonHeaders is a global wrapper methods which delegated to the default client's SetCommonHeaders.

func SetCommonQueryParam

func SetCommonQueryParam(key, value string) *Client

SetCommonQueryParam is a global wrapper methods which delegated to the default client's SetCommonQueryParam.

func SetCommonQueryParams

func SetCommonQueryParams(params map[string]string) *Client

SetCommonQueryParams is a global wrapper methods which delegated to the default client's SetCommonQueryParams.

func SetCommonQueryString

func SetCommonQueryString(query string) *Client

SetCommonQueryString is a global wrapper methods which delegated to the default client's SetCommonQueryString.

func SetCookieJar

func SetCookieJar(jar http.CookieJar) *Client

SetCookieJar is a global wrapper methods which delegated to the default client's SetCookieJar.

func SetDial added in v3.2.0

func SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

SetDial is a global wrapper methods which delegated to the default client's SetDial.

func SetDialTLS added in v3.2.0

func SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

SetDialTLS is a global wrapper methods which delegated to the default client's SetDialTLS.

func SetJsonMarshal

func SetJsonMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetJsonMarshal is a global wrapper methods which delegated to the default client's SetJsonMarshal.

func SetJsonUnmarshal

func SetJsonUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetJsonUnmarshal is a global wrapper methods which delegated to the default client's SetJsonUnmarshal.

func SetLogger

func SetLogger(log Logger) *Client

SetLogger is a global wrapper methods which delegated to the default client's SetLogger.

func SetOutputDirectory

func SetOutputDirectory(dir string) *Client

SetOutputDirectory is a global wrapper methods which delegated to the default client's SetOutputDirectory.

func SetProxy

func SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client

SetProxy is a global wrapper methods which delegated to the default client's SetProxy.

func SetProxyURL

func SetProxyURL(proxyUrl string) *Client

SetProxyURL is a global wrapper methods which delegated to the default client's SetProxyURL.

func SetRedirectPolicy

func SetRedirectPolicy(policies ...RedirectPolicy) *Client

SetRedirectPolicy is a global wrapper methods which delegated to the default client's SetRedirectPolicy.

func SetRootCertFromString

func SetRootCertFromString(pemContent string) *Client

SetRootCertFromString is a global wrapper methods which delegated to the default client's SetRootCertFromString.

func SetRootCertsFromFile

func SetRootCertsFromFile(pemFiles ...string) *Client

SetRootCertsFromFile is a global wrapper methods which delegated to the default client's SetRootCertsFromFile.

func SetScheme

func SetScheme(scheme string) *Client

SetScheme is a global wrapper methods which delegated to the default client's SetScheme.

func SetTLSClientConfig

func SetTLSClientConfig(conf *tls.Config) *Client

SetTLSClientConfig is a global wrapper methods which delegated to the default client's SetTLSClientConfig.

func SetTLSHandshakeTimeout added in v3.2.0

func SetTLSHandshakeTimeout(timeout time.Duration) *Client

SetTLSHandshakeTimeout is a global wrapper methods which delegated to the default client's SetTLSHandshakeTimeout.

func SetTimeout

func SetTimeout(d time.Duration) *Client

SetTimeout is a global wrapper methods which delegated to the default client's SetTimeout.

func SetUserAgent

func SetUserAgent(userAgent string) *Client

SetUserAgent is a global wrapper methods which delegated to the default client's SetUserAgent.

func SetXmlMarshal

func SetXmlMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetXmlMarshal is a global wrapper methods which delegated to the default client's SetXmlMarshal.

func SetXmlUnmarshal

func SetXmlUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetXmlUnmarshal is a global wrapper methods which delegated to the default client's SetXmlUnmarshal.

func (*Client) AddCommonQueryParam

func (c *Client) AddCommonQueryParam(key, value string) *Client

AddCommonQueryParam add a URL query parameter with a key-value pair for all requests.

func (*Client) Clone

func (c *Client) Clone() *Client

Clone copy and returns the Client

func (*Client) DevMode

func (c *Client) DevMode() *Client

DevMode enables: 1. Dump content of all requests and responses to see details. 2. Output debug level log for deeper insights. 3. Trace all requests, so you can get trace info to analyze performance. 4. Set User-Agent to pretend to be a web browser, avoid returning abnormal data from some sites.

func (*Client) DisableAllowGetMethodPayload

func (c *Client) DisableAllowGetMethodPayload() *Client

DisableAllowGetMethodPayload disable sending GET method requests with body.

func (*Client) DisableAutoDecode

func (c *Client) DisableAutoDecode() *Client

DisableAutoDecode disable auto-detect charset and decode to utf-8 (enabled by default).

func (*Client) DisableAutoReadResponse

func (c *Client) DisableAutoReadResponse() *Client

DisableAutoReadResponse disable read response body automatically (enabled by default).

func (*Client) DisableCompression

func (c *Client) DisableCompression() *Client

DisableCompression disables the compression (enabled by default), which prevents the Transport from requesting compression with an "Accept-Encoding: gzip" request header when the Request contains no existing Accept-Encoding value. If the Transport requests gzip on its own and gets a gzipped response, it's transparently decoded in the Response.Body. However, if the user explicitly requested gzip it is not automatically uncompressed.

func (*Client) DisableDebugLog

func (c *Client) DisableDebugLog() *Client

DisableDebugLog disable debug level log (disabled by default).

func (*Client) DisableDumpAll

func (c *Client) DisableDumpAll() *Client

DisableDumpAll disable dump for all requests.

func (*Client) DisableForceHttpVersion added in v3.4.0

func (c *Client) DisableForceHttpVersion() *Client

DisableForceHttpVersion disable force using HTTP1 (disabled by default).

func (*Client) DisableInsecureSkipVerify added in v3.6.0

func (c *Client) DisableInsecureSkipVerify() *Client

DisableInsecureSkipVerify disable send https without verifing the server's certificates (disabled by default).

func (*Client) DisableKeepAlives

func (c *Client) DisableKeepAlives() *Client

DisableKeepAlives disable the HTTP keep-alives (enabled by default) and will only use the connection to the server for a single HTTP request.

This is unrelated to the similarly named TCP keep-alives.

func (*Client) DisableTraceAll

func (c *Client) DisableTraceAll() *Client

DisableTraceAll disable trace for all requests.

func (*Client) EnableAllowGetMethodPayload

func (c *Client) EnableAllowGetMethodPayload() *Client

EnableAllowGetMethodPayload allows sending GET method requests with body.

func (*Client) EnableAutoDecode

func (c *Client) EnableAutoDecode() *Client

EnableAutoDecode enable auto-detect charset and decode to utf-8 (enabled by default).

func (*Client) EnableAutoReadResponse

func (c *Client) EnableAutoReadResponse() *Client

EnableAutoReadResponse enable read response body automatically (enabled by default).

func (*Client) EnableCompression

func (c *Client) EnableCompression() *Client

EnableCompression enables the compression (enabled by default).

func (*Client) EnableDebugLog

func (c *Client) EnableDebugLog() *Client

EnableDebugLog enable debug level log (disabled by default).

func (*Client) EnableDumpAll

func (c *Client) EnableDumpAll() *Client

EnableDumpAll enable dump for all requests, including all content for the request and response by default.

func (*Client) EnableDumpAllAsync

func (c *Client) EnableDumpAllAsync() *Client

EnableDumpAllAsync enable dump for all requests and output asynchronously, can be used for debugging in production environment without affecting performance.

func (*Client) EnableDumpAllTo

func (c *Client) EnableDumpAllTo(output io.Writer) *Client

EnableDumpAllTo enable dump for all requests and output to the specified io.Writer.

func (*Client) EnableDumpAllToFile

func (c *Client) EnableDumpAllToFile(filename string) *Client

EnableDumpAllToFile enable dump for all requests and output to the specified file.

func (*Client) EnableDumpAllWithoutBody

func (c *Client) EnableDumpAllWithoutBody() *Client

EnableDumpAllWithoutBody enable dump for all requests without body, can be used if you only care about the header.

func (*Client) EnableDumpAllWithoutHeader

func (c *Client) EnableDumpAllWithoutHeader() *Client

EnableDumpAllWithoutHeader enable dump for all requests without header, can be used if you only care about the body.

func (*Client) EnableDumpAllWithoutRequest added in v3.1.0

func (c *Client) EnableDumpAllWithoutRequest() *Client

EnableDumpAllWithoutRequest enables dump for all requests without request, can be used if you only care about the response.

func (*Client) EnableDumpAllWithoutRequestBody

func (c *Client) EnableDumpAllWithoutRequestBody() *Client

EnableDumpAllWithoutRequestBody enable dump for all requests without request body, can be used in the upload request to avoid dumping the unreadable binary content.

func (*Client) EnableDumpAllWithoutResponse

func (c *Client) EnableDumpAllWithoutResponse() *Client

EnableDumpAllWithoutResponse enable dump for all requests without response, can be used if you only care about the request.

func (*Client) EnableDumpAllWithoutResponseBody

func (c *Client) EnableDumpAllWithoutResponseBody() *Client

EnableDumpAllWithoutResponseBody enable dump for all requests without response body, can be used in the download request to avoid dumping the unreadable binary content.

func (*Client) EnableForceHTTP1 added in v3.2.0

func (c *Client) EnableForceHTTP1() *Client

EnableForceHTTP1 enable force using HTTP1 (disabled by default).

func (*Client) EnableForceHTTP2 added in v3.4.0

func (c *Client) EnableForceHTTP2() *Client

EnableForceHTTP2 enable force using HTTP2 for https requests (disabled by default).

func (*Client) EnableInsecureSkipVerify added in v3.6.0

func (c *Client) EnableInsecureSkipVerify() *Client

EnableInsecureSkipVerify enable send https without verifing the server's certificates (disabled by default).

func (*Client) EnableKeepAlives

func (c *Client) EnableKeepAlives() *Client

EnableKeepAlives enables HTTP keep-alives (enabled by default).

func (*Client) EnableTraceAll

func (c *Client) EnableTraceAll() *Client

EnableTraceAll enable trace for all requests.

func (*Client) GetTLSClientConfig added in v3.6.0

func (c *Client) GetTLSClientConfig() *tls.Config

GetTLSClientConfig return the underlying tls.Config.

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

NewRequest is the alias of R()

func (*Client) OnAfterResponse

func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client

OnAfterResponse add a response middleware which hooks after response received.

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client

OnBeforeRequest add a request middleware which hooks before request sent.

func (*Client) R

func (c *Client) R() *Request

R create a new request.

func (*Client) SetAutoDecodeAllContentType added in v3.3.0

func (c *Client) SetAutoDecodeAllContentType() *Client

SetAutoDecodeAllContentType enable try auto-detect charset and decode all content type to utf-8.

func (*Client) SetAutoDecodeContentType

func (c *Client) SetAutoDecodeContentType(contentTypes ...string) *Client

SetAutoDecodeContentType set the content types that will be auto-detected and decode to utf-8 (e.g. "json", "xml", "html", "text").

func (*Client) SetAutoDecodeContentTypeFunc added in v3.3.0

func (c *Client) SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Client

SetAutoDecodeContentTypeFunc set the function that determines whether the specified `Content-Type` should be auto-detected and decode to utf-8.

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(u string) *Client

SetBaseURL set the default base URL, will be used if request URL is a relative URL.

func (*Client) SetCertFromFile

func (c *Client) SetCertFromFile(certFile, keyFile string) *Client

SetCertFromFile helps to set client certificates from cert and key file.

func (*Client) SetCerts

func (c *Client) SetCerts(certs ...tls.Certificate) *Client

SetCerts set client certificates.

func (*Client) SetCommonBasicAuth

func (c *Client) SetCommonBasicAuth(username, password string) *Client

SetCommonBasicAuth set the basic auth for all requests.

func (*Client) SetCommonBearerAuthToken

func (c *Client) SetCommonBearerAuthToken(token string) *Client

SetCommonBearerAuthToken set the bearer auth token for all requests.

func (*Client) SetCommonContentType

func (c *Client) SetCommonContentType(ct string) *Client

SetCommonContentType set the `Content-Type` header for all requests.

func (*Client) SetCommonCookies

func (c *Client) SetCommonCookies(cookies ...*http.Cookie) *Client

SetCommonCookies set HTTP cookies for all requests.

func (*Client) SetCommonDumpOptions

func (c *Client) SetCommonDumpOptions(opt *DumpOptions) *Client

SetCommonDumpOptions configures the underlying Transport's DumpOptions for all requests.

func (*Client) SetCommonFormData

func (c *Client) SetCommonFormData(data map[string]string) *Client

SetCommonFormData set the form data from map for all requests which request method allows payload.

func (*Client) SetCommonFormDataFromValues

func (c *Client) SetCommonFormDataFromValues(data urlpkg.Values) *Client

SetCommonFormDataFromValues set the form data from url.Values for all requests which request method allows payload.

func (*Client) SetCommonHeader

func (c *Client) SetCommonHeader(key, value string) *Client

SetCommonHeader set a header for all requests.

func (*Client) SetCommonHeaders

func (c *Client) SetCommonHeaders(hdrs map[string]string) *Client

SetCommonHeaders set headers for all requests.

func (*Client) SetCommonQueryParam

func (c *Client) SetCommonQueryParam(key, value string) *Client

SetCommonQueryParam set a URL query parameter with a key-value pair for all requests.

func (*Client) SetCommonQueryParams

func (c *Client) SetCommonQueryParams(params map[string]string) *Client

SetCommonQueryParams set URL query parameters with a map for all requests.

func (*Client) SetCommonQueryString

func (c *Client) SetCommonQueryString(query string) *Client

SetCommonQueryString set URL query parameters with a raw query string for all requests.

func (*Client) SetCookieJar

func (c *Client) SetCookieJar(jar http.CookieJar) *Client

SetCookieJar set the `CookeJar` to the underlying `http.Client`.

func (*Client) SetDial added in v3.2.0

func (c *Client) SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

SetDial set the customized `DialContext` function to Transport.

func (*Client) SetDialTLS added in v3.2.0

func (c *Client) SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Client

SetDialTLS set the customized `DialTLSContext` function to Transport. Make sure the returned `conn` implements TLSConn if you want your customized `conn` supports HTTP2.

func (*Client) SetJsonMarshal

func (c *Client) SetJsonMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetJsonMarshal set the JSON marshal function which will be used to marshal request body.

func (*Client) SetJsonUnmarshal

func (c *Client) SetJsonUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetJsonUnmarshal set the JSON unmarshal function which will be used to unmarshal response body.

func (*Client) SetLogger

func (c *Client) SetLogger(log Logger) *Client

SetLogger set the customized logger for client, will disable log if set to nil.

func (*Client) SetOutputDirectory

func (c *Client) SetOutputDirectory(dir string) *Client

SetOutputDirectory set output directory that response will be downloaded to.

func (*Client) SetProxy

func (c *Client) SetProxy(proxy func(*http.Request) (*urlpkg.URL, error)) *Client

SetProxy set the proxy function.

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxyUrl string) *Client

SetProxyURL set proxy from the proxy URL.

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client

SetRedirectPolicy set the RedirectPolicy which controls the behavior of receiving redirect responses (usually responses with 301 and 302 status code), see the predefined AllowedDomainRedirectPolicy, AllowedHostRedirectPolicy, MaxRedirectPolicy, NoRedirectPolicy, SameDomainRedirectPolicy and SameHostRedirectPolicy.

func (*Client) SetRootCertFromString

func (c *Client) SetRootCertFromString(pemContent string) *Client

SetRootCertFromString set root certificates from string.

func (*Client) SetRootCertsFromFile

func (c *Client) SetRootCertsFromFile(pemFiles ...string) *Client

SetRootCertsFromFile set root certificates from files.

func (*Client) SetScheme

func (c *Client) SetScheme(scheme string) *Client

SetScheme set the default scheme for client, will be used when there is no scheme in the request URL (e.g. "github.com/imroc/req").

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(conf *tls.Config) *Client

SetTLSClientConfig set the TLS client config. Be careful! Usually you don't need this, you can directly set the tls configuration with methods like EnableInsecureSkipVerify, SetCerts etc. Or you can call GetTLSClientConfig to get the current tls configuration to avoid overwriting some important configurations, such as not setting NextProtos will not use http2 by default.

func (*Client) SetTLSHandshakeTimeout added in v3.2.0

func (c *Client) SetTLSHandshakeTimeout(timeout time.Duration) *Client

SetTLSHandshakeTimeout set the TLS handshake timeout.

func (*Client) SetTimeout

func (c *Client) SetTimeout(d time.Duration) *Client

SetTimeout set timeout for all requests.

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(userAgent string) *Client

SetUserAgent set the "User-Agent" header for all requests.

func (*Client) SetXmlMarshal

func (c *Client) SetXmlMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetXmlMarshal set the XML marshal function which will be used to marshal request body.

func (*Client) SetXmlUnmarshal

func (c *Client) SetXmlUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetXmlUnmarshal set the XML unmarshal function which will be used to unmarshal response body.

type ContentDisposition added in v3.5.1

type ContentDisposition struct {
	// contains filtered or unexported fields
}

ContentDisposition represents parameters in `Content-Disposition` MIME header of multipart request.

func (*ContentDisposition) Add added in v3.5.1

func (c *ContentDisposition) Add(key, value string) *ContentDisposition

func (*ContentDisposition) String added in v3.5.1

func (c *ContentDisposition) String() string

type DumpOptions

type DumpOptions struct {
	Output         io.Writer
	RequestHeader  bool
	RequestBody    bool
	ResponseHeader bool
	ResponseBody   bool
	Async          bool
}

DumpOptions controls the dump behavior.

func (*DumpOptions) Clone

func (do *DumpOptions) Clone() *DumpOptions

type FileUpload added in v3.5.0

type FileUpload struct {
	// "name" parameter in `Content-Disposition`
	ParamName string
	// "filename" parameter in `Content-Disposition`
	FileName string
	// The file to be uploaded.
	File io.Reader

	// According to the HTTP specification, this should be nil,
	// but some servers may not follow the specification and
	// requires `Content-Disposition` parameters more than just
	// "name" and "filename".
	ExtraContentDisposition *ContentDisposition
}

FileUpload represents a "form-data" multipart

type HttpVersion added in v3.4.0

type HttpVersion string
const (
	HTTP1 HttpVersion = "1.1"
	HTTP2 HttpVersion = "2"
)

type Logger

type Logger interface {
	Errorf(format string, v ...interface{})
	Warnf(format string, v ...interface{})
	Debugf(format string, v ...interface{})
}

Logger is the abstract logging interface, gives control to the Req users, choice of the logger.

func NewLogger

func NewLogger(output io.Writer, prefix string, flag int) Logger

NewLogger create a Logger wraps the *log.Logger

type RedirectPolicy

type RedirectPolicy func(req *http.Request, via []*http.Request) error

func AllowedDomainRedirectPolicy

func AllowedDomainRedirectPolicy(hosts ...string) RedirectPolicy

AllowedDomainRedirectPolicy allows redirect only if the redirected domain match one of the domain that specified.

func AllowedHostRedirectPolicy

func AllowedHostRedirectPolicy(hosts ...string) RedirectPolicy

AllowedHostRedirectPolicy allows redirect only if the redirected host match one of the host that specified.

func MaxRedirectPolicy

func MaxRedirectPolicy(noOfRedirect int) RedirectPolicy

MaxRedirectPolicy specifies the max number of redirect

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy disable redirect behaviour

func SameDomainRedirectPolicy

func SameDomainRedirectPolicy() RedirectPolicy

func SameHostRedirectPolicy

func SameHostRedirectPolicy() RedirectPolicy

SameHostRedirectPolicy allows redirect only if the redirected host is the same as original host, e.g. redirect to "www.imroc.cc" from "imroc.cc" is not the allowed.

type Request

type Request struct {
	URL         string
	PathParams  map[string]string
	QueryParams urlpkg.Values
	FormData    urlpkg.Values
	Headers     http.Header
	Cookies     []*http.Cookie
	Result      interface{}
	Error       interface{}

	RawRequest *http.Request
	StartTime  time.Time
	// contains filtered or unexported fields
}

Request struct is used to compose and fire individual request from req client. Request provides lots of chainable settings which can override client level settings.

func AddQueryParam

func AddQueryParam(key, value string) *Request

AddQueryParam is a global wrapper methods which delegated to the default client, create a request and AddQueryParam for request.

func DisableTrace

func DisableTrace() *Request

DisableTrace is a global wrapper methods which delegated to the default client, create a request and DisableTrace for request.

func EnableDump

func EnableDump() *Request

EnableDump is a global wrapper methods which delegated to the default client, create a request and EnableDump for request.

func EnableDumpTo

func EnableDumpTo(output io.Writer) *Request

EnableDumpTo is a global wrapper methods which delegated to the default client, create a request and EnableDumpTo for request.

func EnableDumpToFile

func EnableDumpToFile(filename string) *Request

EnableDumpToFile is a global wrapper methods which delegated to the default client, create a request and EnableDumpToFile for request.

func EnableDumpWithoutBody

func EnableDumpWithoutBody() *Request

EnableDumpWithoutBody is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutBody for request.

func EnableDumpWithoutHeader

func EnableDumpWithoutHeader() *Request

EnableDumpWithoutHeader is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutHeader for request.

func EnableDumpWithoutRequest

func EnableDumpWithoutRequest() *Request

EnableDumpWithoutRequest is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutRequest for request.

func EnableDumpWithoutRequestBody added in v3.1.0

func EnableDumpWithoutRequestBody() *Request

EnableDumpWithoutRequestBody is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutRequestBody for request.

func EnableDumpWithoutResponse

func EnableDumpWithoutResponse() *Request

EnableDumpWithoutResponse is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutResponse for request.

func EnableDumpWithoutResponseBody added in v3.1.0

func EnableDumpWithoutResponseBody() *Request

EnableDumpWithoutResponseBody is a global wrapper methods which delegated to the default client, create a request and EnableDumpWithoutResponseBody for request.

func EnableTrace

func EnableTrace() *Request

EnableTrace is a global wrapper methods which delegated to the default client, create a request and EnableTrace for request.

func NewRequest

func NewRequest() *Request

NewRequest is a global wrapper methods which delegated to the default client's NewRequest.

func R

func R() *Request

R is a global wrapper methods which delegated to the default client's R().

func SetBasicAuth

func SetBasicAuth(username, password string) *Request

SetBasicAuth is a global wrapper methods which delegated to the default client, create a request and SetBasicAuth for request.

func SetBearerAuthToken

func SetBearerAuthToken(token string) *Request

SetBearerAuthToken is a global wrapper methods which delegated to the default client, create a request and SetBearerAuthToken for request.

func SetBody

func SetBody(body interface{}) *Request

SetBody is a global wrapper methods which delegated to the default client, create a request and SetBody for request.

func SetBodyBytes

func SetBodyBytes(body []byte) *Request

SetBodyBytes is a global wrapper methods which delegated to the default client, create a request and SetBodyBytes for request.

func SetBodyJsonBytes

func SetBodyJsonBytes(body []byte) *Request

SetBodyJsonBytes is a global wrapper methods which delegated to the default client, create a request and SetBodyJsonBytes for request.

func SetBodyJsonMarshal

func SetBodyJsonMarshal(v interface{}) *Request

SetBodyJsonMarshal is a global wrapper methods which delegated to the default client, create a request and SetBodyJsonMarshal for request.

func SetBodyJsonString

func SetBodyJsonString(body string) *Request

SetBodyJsonString is a global wrapper methods which delegated to the default client, create a request and SetBodyJsonString for request.

func SetBodyString

func SetBodyString(body string) *Request

SetBodyString is a global wrapper methods which delegated to the default client, create a request and SetBodyString for request.

func SetBodyXmlBytes

func SetBodyXmlBytes(body []byte) *Request

SetBodyXmlBytes is a global wrapper methods which delegated to the default client, create a request and SetBodyXmlBytes for request.

func SetBodyXmlMarshal

func SetBodyXmlMarshal(v interface{}) *Request

SetBodyXmlMarshal is a global wrapper methods which delegated to the default client, create a request and SetBodyXmlMarshal for request.

func SetBodyXmlString

func SetBodyXmlString(body string) *Request

SetBodyXmlString is a global wrapper methods which delegated to the default client, create a request and SetBodyXmlString for request.

func SetContentType

func SetContentType(contentType string) *Request

SetContentType is a global wrapper methods which delegated to the default client, create a request and SetContentType for request.

func SetContext

func SetContext(ctx context.Context) *Request

SetContext is a global wrapper methods which delegated to the default client, create a request and SetContext for request.

func SetCookies

func SetCookies(cookies ...*http.Cookie) *Request

SetCookies is a global wrapper methods which delegated to the default client, create a request and SetCookies for request.

func SetDumpOptions

func SetDumpOptions(opt *DumpOptions) *Request

func SetError

func SetError(error interface{}) *Request

SetError is a global wrapper methods which delegated to the default client, create a request and SetError for request.

func SetFile

func SetFile(paramName, filePath string) *Request

SetFile is a global wrapper methods which delegated to the default client, create a request and SetFile for request.

func SetFileBytes added in v3.5.0

func SetFileBytes(paramName, filename string, content []byte) *Request

SetFileBytes is a global wrapper methods which delegated to the default client, create a request and SetFileBytes for request.

func SetFileReader

func SetFileReader(paramName, filePath string, reader io.Reader) *Request

SetFileReader is a global wrapper methods which delegated to the default client, create a request and SetFileReader for request.

func SetFileUpload added in v3.5.0

func SetFileUpload(f FileUpload) *Request

SetFileUpload is a global wrapper methods which delegated to the default client, create a request and SetFileUpload for request.

func SetFiles

func SetFiles(files map[string]string) *Request

SetFiles is a global wrapper methods which delegated to the default client, create a request and SetFiles for request.

func SetFormData

func SetFormData(data map[string]string) *Request

SetFormData is a global wrapper methods which delegated to the default client, create a request and SetFormData for request.

func SetFormDataFromValues

func SetFormDataFromValues(data urlpkg.Values) *Request

SetFormDataFromValues is a global wrapper methods which delegated to the default client, create a request and SetFormDataFromValues for request.

func SetHeader

func SetHeader(key, value string) *Request

SetHeader is a global wrapper methods which delegated to the default client, create a request and SetHeader for request.

func SetHeaders

func SetHeaders(hdrs map[string]string) *Request

SetHeaders is a global wrapper methods which delegated to the default client, create a request and SetHeaders for request.

func SetOutput

func SetOutput(output io.Writer) *Request

SetOutput is a global wrapper methods which delegated to the default client, create a request and SetOutput for request.

func SetOutputFile

func SetOutputFile(file string) *Request

SetOutputFile is a global wrapper methods which delegated to the default client, create a request and SetOutputFile for request.

func SetPathParam

func SetPathParam(key, value string) *Request

SetPathParam is a global wrapper methods which delegated to the default client, create a request and SetPathParam for request.

func SetPathParams

func SetPathParams(params map[string]string) *Request

SetPathParams is a global wrapper methods which delegated to the default client, create a request and SetPathParams for request.

func SetQueryParam

func SetQueryParam(key, value string) *Request

SetQueryParam is a global wrapper methods which delegated to the default client, create a request and SetQueryParam for request.

func SetQueryParams

func SetQueryParams(params map[string]string) *Request

SetQueryParams is a global wrapper methods which delegated to the default client, create a request and SetQueryParams for request.

func SetQueryString

func SetQueryString(query string) *Request

SetQueryString is a global wrapper methods which delegated to the default client, create a request and SetQueryString for request.

func SetResult

func SetResult(result interface{}) *Request

SetResult is a global wrapper methods which delegated to the default client, create a request and SetResult for request.

func (*Request) AddQueryParam

func (r *Request) AddQueryParam(key, value string) *Request

AddQueryParam add a URL query parameter for the request.

func (*Request) Context

func (r *Request) Context() context.Context

Context method returns the Context if its already set in request otherwise it creates new one using `context.Background()`.

func (*Request) Delete

func (r *Request) Delete(url string) (*Response, error)

Delete fires http request with DELETE method and the specified URL.

func (*Request) DisableTrace

func (r *Request) DisableTrace() *Request

DisableTrace disables trace.

func (*Request) EnableDump

func (r *Request) EnableDump() *Request

EnableDump enables dump, including all content for the request and response by default.

func (*Request) EnableDumpTo

func (r *Request) EnableDumpTo(output io.Writer) *Request

EnableDumpTo enables dump and save to the specified io.Writer.

func (*Request) EnableDumpToFile

func (r *Request) EnableDumpToFile(filename string) *Request

EnableDumpToFile enables dump and save to the specified filename.

func (*Request) EnableDumpWithoutBody

func (r *Request) EnableDumpWithoutBody() *Request

EnableDumpWithoutBody enables dump only header for the request and response.

func (*Request) EnableDumpWithoutHeader

func (r *Request) EnableDumpWithoutHeader() *Request

EnableDumpWithoutHeader enables dump only body for the request and response.

func (*Request) EnableDumpWithoutRequest

func (r *Request) EnableDumpWithoutRequest() *Request

EnableDumpWithoutRequest enables dump only response.

func (*Request) EnableDumpWithoutRequestBody added in v3.1.0

func (r *Request) EnableDumpWithoutRequestBody() *Request

EnableDumpWithoutRequestBody enables dump with request body excluded, can be used in upload request to avoid dump the unreadable binary content.

func (*Request) EnableDumpWithoutResponse

func (r *Request) EnableDumpWithoutResponse() *Request

EnableDumpWithoutResponse enables dump only request.

func (*Request) EnableDumpWithoutResponseBody added in v3.1.0

func (r *Request) EnableDumpWithoutResponseBody() *Request

EnableDumpWithoutResponseBody enables dump with response body excluded, can be used in download request to avoid dump the unreadable binary content.

func (*Request) EnableTrace

func (r *Request) EnableTrace() *Request

EnableTrace enables trace.

func (*Request) Get

func (r *Request) Get(url string) (*Response, error)

Get fires http request with GET method and the specified URL.

func (*Request) Head

func (r *Request) Head(url string) (*Response, error)

Head fires http request with HEAD method and the specified URL.

func (*Request) MustDelete

func (r *Request) MustDelete(url string) *Response

MustDelete like Delete, panic if error happens, should only be used to test without error handling.

func (*Request) MustGet

func (r *Request) MustGet(url string) *Response

MustGet like Get, panic if error happens, should only be used to test without error handling.

func (*Request) MustHead

func (r *Request) MustHead(url string) *Response

MustHead like Head, panic if error happens, should only be used to test without error handling.

func (*Request) MustOptions

func (r *Request) MustOptions(url string) *Response

MustOptions like Options, panic if error happens, should only be used to test without error handling.

func (*Request) MustPatch

func (r *Request) MustPatch(url string) *Response

MustPatch like Patch, panic if error happens, should only be used to test without error handling.

func (*Request) MustPost

func (r *Request) MustPost(url string) *Response

MustPost like Post, panic if error happens. should only be used to test without error handling.

func (*Request) MustPut

func (r *Request) MustPut(url string) *Response

MustPut like Put, panic if error happens, should only be used to test without error handling.

func (*Request) Options

func (r *Request) Options(url string) (*Response, error)

Options fires http request with OPTIONS method and the specified URL.

func (*Request) Patch

func (r *Request) Patch(url string) (*Response, error)

Patch fires http request with PATCH method and the specified URL.

func (*Request) Post

func (r *Request) Post(url string) (*Response, error)

Post fires http request with POST method and the specified URL.

func (*Request) Put

func (r *Request) Put(url string) (*Response, error)

Put fires http request with PUT method and the specified URL.

func (*Request) Send

func (r *Request) Send(method, url string) (*Response, error)

Send fires http request and return the *Response which is always not nil, and the error is not nil if some error happens.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth set basic auth for the request.

func (*Request) SetBearerAuthToken

func (r *Request) SetBearerAuthToken(token string) *Request

SetBearerAuthToken set bearer auth token for the request.

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody set the request body, accepts string, []byte, io.Reader, map and struct.

func (*Request) SetBodyBytes

func (r *Request) SetBodyBytes(body []byte) *Request

SetBodyBytes set the request body as []byte.

func (*Request) SetBodyJsonBytes

func (r *Request) SetBodyJsonBytes(body []byte) *Request

SetBodyJsonBytes set the request body as []byte and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyJsonMarshal

func (r *Request) SetBodyJsonMarshal(v interface{}) *Request

SetBodyJsonMarshal set the request body that marshaled from object, and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyJsonString

func (r *Request) SetBodyJsonString(body string) *Request

SetBodyJsonString set the request body as string and set Content-Type header as "application/json; charset=utf-8"

func (*Request) SetBodyString

func (r *Request) SetBodyString(body string) *Request

SetBodyString set the request body as string.

func (*Request) SetBodyXmlBytes

func (r *Request) SetBodyXmlBytes(body []byte) *Request

SetBodyXmlBytes set the request body as []byte and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetBodyXmlMarshal

func (r *Request) SetBodyXmlMarshal(v interface{}) *Request

SetBodyXmlMarshal set the request body that marshaled from object, and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetBodyXmlString

func (r *Request) SetBodyXmlString(body string) *Request

SetBodyXmlString set the request body as string and set Content-Type header as "text/xml; charset=utf-8"

func (*Request) SetContentType

func (r *Request) SetContentType(contentType string) *Request

SetContentType set the `Content-Type` for the request.

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context) *Request

SetContext method sets the context.Context for current Request. It allows to interrupt the request execution if ctx.Done() channel is closed. See https://blog.golang.org/context article and the "context" package documentation.

func (*Request) SetCookies

func (r *Request) SetCookies(cookies ...*http.Cookie) *Request

SetCookies set http cookies for the request.

func (*Request) SetDumpOptions

func (r *Request) SetDumpOptions(opt *DumpOptions) *Request

SetDumpOptions sets DumpOptions at request level.

func (*Request) SetError

func (r *Request) SetError(error interface{}) *Request

SetError set the result that response body will be unmarshaled to if request is error ( status `code >= 400`).

func (*Request) SetFile

func (r *Request) SetFile(paramName, filePath string) *Request

SetFile set up a multipart form from file path to upload, which read file from filePath automatically to upload.

func (*Request) SetFileBytes added in v3.5.0

func (r *Request) SetFileBytes(paramName, filename string, content []byte) *Request

SetFileBytes set up a multipart form with given []byte to upload.

func (*Request) SetFileReader

func (r *Request) SetFileReader(paramName, filename string, reader io.Reader) *Request

SetFileReader set up a multipart form with a reader to upload file.

func (*Request) SetFileUpload added in v3.5.0

func (r *Request) SetFileUpload(f FileUpload) *Request

SetFileUpload set the fully custimized multipart file upload options.

func (*Request) SetFiles

func (r *Request) SetFiles(files map[string]string) *Request

SetFiles set up a multipart form from a map to upload, which key is the parameter name, and value is the file path.

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData set the form data from a map, will not been used if request method does not allow payload.

func (*Request) SetFormDataFromValues

func (r *Request) SetFormDataFromValues(data urlpkg.Values) *Request

SetFormDataFromValues set the form data from url.Values, will not been used if request method does not allow payload.

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader set a header for the request.

func (*Request) SetHeaders

func (r *Request) SetHeaders(hdrs map[string]string) *Request

SetHeaders set headers from a map for the request.

func (*Request) SetOutput

func (r *Request) SetOutput(output io.Writer) *Request

SetOutput set the io.Writer that response body will be downloaded to.

func (*Request) SetOutputFile

func (r *Request) SetOutputFile(file string) *Request

SetOutputFile set the file that response body will be downloaded to.

func (*Request) SetPathParam

func (r *Request) SetPathParam(key, value string) *Request

SetPathParam set a URL path parameter for the request.

func (*Request) SetPathParams

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams set URL path parameters from a map for the request.

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(key, value string) *Request

SetQueryParam set an URL query parameter for the request.

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams set URL query parameters from a map for the request.

func (*Request) SetQueryString

func (r *Request) SetQueryString(query string) *Request

SetQueryString set URL query parameters for the request using raw query string.

func (*Request) SetResult

func (r *Request) SetResult(result interface{}) *Request

SetResult set the result that response body will be unmarshaled to if request is success (status `code >= 200 and <= 299`).

func (*Request) TraceInfo

func (r *Request) TraceInfo() TraceInfo

TraceInfo returns the trace information, only available if trace is enabled (see Request.EnableTrace and Client.EnableTraceAll).

type RequestMiddleware

type RequestMiddleware func(*Client, *Request) error

RequestMiddleware type is for request middleware, called before a request is sent

type Response

type Response struct {
	*http.Response
	Request *Request
	// contains filtered or unexported fields
}

Response is the http response.

func Delete

func Delete(url string) (*Response, error)

Delete is a global wrapper methods which delegated to the default client, create a request and Delete for request.

func Get

func Get(url string) (*Response, error)

Get is a global wrapper methods which delegated to the default client, create a request and Get for request.

func Head(url string) (*Response, error)

Head is a global wrapper methods which delegated to the default client, create a request and Head for request.

func MustDelete

func MustDelete(url string) *Response

MustDelete is a global wrapper methods which delegated to the default client, create a request and MustDelete for request.

func MustGet

func MustGet(url string) *Response

MustGet is a global wrapper methods which delegated to the default client, create a request and MustGet for request.

func MustHead

func MustHead(url string) *Response

MustHead is a global wrapper methods which delegated to the default client, create a request and MustHead for request.

func MustOptions

func MustOptions(url string) *Response

MustOptions is a global wrapper methods which delegated to the default client, create a request and MustOptions for request.

func MustPatch

func MustPatch(url string) *Response

MustPatch is a global wrapper methods which delegated to the default client, create a request and MustPatch for request.

func MustPost

func MustPost(url string) *Response

MustPost is a global wrapper methods which delegated to the default client, create a request and Get for request.

func MustPut

func MustPut(url string) *Response

MustPut is a global wrapper methods which delegated to the default client, create a request and MustPut for request.

func Options

func Options(url string) (*Response, error)

Options is a global wrapper methods which delegated to the default client, create a request and Options for request.

func Patch

func Patch(url string) (*Response, error)

Patch is a global wrapper methods which delegated to the default client, create a request and Patch for request.

func Post

func Post(url string) (*Response, error)

Post is a global wrapper methods which delegated to the default client, create a request and Post for request.

func Put

func Put(url string) (*Response, error)

Put is a global wrapper methods which delegated to the default client, create a request and Put for request.

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes return the response body as []bytes that hava already been read, could be nil if not read, the following cases are already read:

  1. `Request.SetResult` or `Request.SetError` is called.
  2. `Client.DisableAutoReadResponse(false)` is not called, also `Request.SetOutput` and `Request.SetOutputFile` is not called.

func (*Response) Dump

func (r *Response) Dump() string

Dump return the string content that have been dumped for the request. `Request.Dump` or `Request.DumpXXX` MUST have been called.

func (*Response) Error

func (r *Response) Error() interface{}

Error returns the error object if it has one.

func (*Response) GetContentType

func (r *Response) GetContentType() string

GetContentType return the `Content-Type` header value.

func (*Response) IsError

func (r *Response) IsError() bool

IsError method returns true if HTTP status `code >= 400` otherwise false.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt returns the timestamp that response we received.

func (*Response) Result

func (r *Response) Result() interface{}

Result returns the response value as an object if it has one

func (*Response) String

func (r *Response) String() string

String returns the response body as string that hava already been read, could be nil if not read, the following cases are already read:

  1. `Request.SetResult` or `Request.SetError` is called.
  2. `Client.DisableAutoReadResponse(false)` is not called, also `Request.SetOutput` and `Request.SetOutputFile` is not called.

func (*Response) ToBytes

func (r *Response) ToBytes() ([]byte, error)

ToBytes returns the response body as []byte, read body if not have been read.

func (*Response) ToString

func (r *Response) ToString() (string, error)

ToString returns the response body as string, read body if not have been read.

func (*Response) TotalTime

func (r *Response) TotalTime() time.Duration

TotalTime returns the total time of the request, from request we sent to response we received.

func (*Response) TraceInfo

func (r *Response) TraceInfo() TraceInfo

TraceInfo returns the TraceInfo from Request.

func (*Response) Unmarshal

func (r *Response) Unmarshal(v interface{}) error

Unmarshal unmarshals response body into the specified object according to response `Content-Type`.

func (*Response) UnmarshalJson

func (r *Response) UnmarshalJson(v interface{}) error

UnmarshalJson unmarshals JSON response body into the specified object.

func (*Response) UnmarshalXml

func (r *Response) UnmarshalXml(v interface{}) error

UnmarshalXml unmarshals XML response body into the specified object.

type ResponseMiddleware

type ResponseMiddleware func(*Client, *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type ResponseOptions

type ResponseOptions struct {
	// DisableAutoDecode, if true, prevents auto detect response
	// body's charset and decode it to utf-8
	DisableAutoDecode bool

	// AutoDecodeContentType specifies an optional function for determine
	// whether the response body should been auto decode to utf-8.
	// Only valid when DisableAutoDecode is true.
	AutoDecodeContentType func(contentType string) bool
}

ResponseOptions determines that how should the response been processed.

type TLSConn added in v3.2.0

type TLSConn interface {
	net.Conn
	ConnectionState() tls.ConnectionState
	Handshake() error
}

TLSConn is the recommended interface for the connection returned by the DailTLS function (Client.SetDialTLS, Transport.DialTLSContext), so that the TLS handshake negotiation can automatically decide whether to use HTTP2 or HTTP1 (ALPN). If this interface is not implemented, HTTP1 will be used by default.

type TraceInfo

type TraceInfo struct {
	// DNSLookupTime is a duration that transport took to perform
	// DNS lookup.
	DNSLookupTime time.Duration

	// ConnectTime is a duration that took to obtain a successful connection.
	ConnectTime time.Duration

	// TCPConnectTime is a duration that took to obtain the TCP connection.
	TCPConnectTime time.Duration

	// TLSHandshakeTime is a duration that TLS handshake took place.
	TLSHandshakeTime time.Duration

	// FirstResponseTime is a duration that server took to respond first byte since
	// connection ready (after tls handshake if it's tls and not a reused connection).
	FirstResponseTime time.Duration

	// ResponseTime is a duration since first response byte from server to
	// request completion.
	ResponseTime time.Duration

	// TotalTime is a duration that total request took end-to-end.
	TotalTime time.Duration

	// IsConnReused is whether this connection has been previously
	// used for another HTTP request.
	IsConnReused bool

	// IsConnWasIdle is whether this connection was obtained from an
	// idle pool.
	IsConnWasIdle bool

	// ConnIdleTime is a duration how long the connection was previously
	// idle, if IsConnWasIdle is true.
	ConnIdleTime time.Duration

	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr
}

func (TraceInfo) Blame

func (t TraceInfo) Blame() string

func (TraceInfo) String

func (t TraceInfo) String() string

type Transport

type Transport struct {

	// Force using specific http version
	ForceHttpVersion HttpVersion

	// Proxy specifies a function to return a proxy for a given
	// Request. If the function returns a non-nil error, the
	// request is aborted with the provided error.
	//
	// The proxy type is determined by the URL scheme. "http",
	// "https", and "socks5" are supported. If the scheme is empty,
	// "http" is assumed.
	//
	// If Proxy is nil or returns a nil *URL, no proxy is used.
	Proxy func(*http.Request) (*url.URL, error)

	// DialContext specifies the dial function for creating unencrypted TCP connections.
	// If DialContext is nil, then the transport dials using package net.
	//
	// DialContext runs concurrently with calls to RoundTrip.
	// A RoundTrip call that initiates a dial may end up using
	// a connection dialed previously when the earlier connection
	// becomes idle before the later DialContext completes.
	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// DialTLSContext specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// If DialTLSContext is nil, DialContext and TLSClientConfig are used.
	//
	// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
	// requests and the TLSClientConfig and TLSHandshakeTimeout
	// are ignored. The returned net.Conn is assumed to already be
	// past the TLS handshake.
	DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client.
	// If nil, the default configuration is used.
	// If non-nil, HTTP/2 support may not be enabled by default.
	TLSClientConfig *tls.Config

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration

	// DisableKeepAlives, if true, disables HTTP keep-alives and
	// will only use the connection to the server for a single
	// HTTP request.
	//
	// This is unrelated to the similarly named TCP keep-alives.
	DisableKeepAlives bool

	// DisableCompression, if true, prevents the Transport from
	// requesting compression with an "Accept-Encoding: gzip"
	// request header when the Request contains no existing
	// Accept-Encoding value. If the Transport requests gzip on
	// its own and gets a gzipped response, it's transparently
	// decoded in the Response.Body. However, if the user
	// explicitly requested gzip it is not automatically
	// uncompressed.
	DisableCompression bool

	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// defaultMaxIdleConnsPerHost is used.
	MaxIdleConnsPerHost int

	// MaxConnsPerHost optionally limits the total number of
	// connections per host, including connections in the dialing,
	// active, and idle states. On limit violation, dials will block.
	//
	// Zero means no limit.
	MaxConnsPerHost int

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration

	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration

	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration

	// TLSNextProto specifies how the Transport switches to an
	// alternate protocol (such as HTTP/2) after a TLS ALPN
	// protocol negotiation. If Transport dials an TLS connection
	// with a non-empty protocol name and TLSNextProto contains a
	// map entry for that key (such as "h2"), then the func is
	// called with the request's authority (such as "example.com"
	// or "example.com:1234") and the TLS connection. The function
	// must return a http.RoundTripper that then handles the request.
	// If TLSNextProto is not nil, HTTP/2 support is not enabled
	// automatically.
	TLSNextProto map[string]func(authority string, c TLSConn) http.RoundTripper

	// ProxyConnectHeader optionally specifies headers to send to
	// proxies during CONNECT requests.
	// To set the header dynamically, see GetProxyConnectHeader.
	ProxyConnectHeader http.Header

	// GetProxyConnectHeader optionally specifies a func to return
	// headers to send to proxyURL during a CONNECT request to the
	// ip:port target.
	// If it returns an error, the Transport's RoundTrip fails with
	// that error. It can return (nil, nil) to not add headers.
	// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
	// ignored.
	GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)

	// MaxResponseHeaderBytes specifies a limit on how many
	// response bytes are allowed in the server's response
	// header.
	//
	// Zero means to use a default limit.
	MaxResponseHeaderBytes int64

	// WriteBufferSize specifies the size of the write buffer used
	// when writing to the transport.
	// If zero, a default (currently 4KB) is used.
	WriteBufferSize int

	// ReadBufferSize specifies the size of the read buffer used
	// when reading from the transport.
	// If zero, a default (currently 4KB) is used.
	ReadBufferSize int

	// ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
	// Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
	// By default, use of any those fields conservatively disables HTTP/2.
	// To use a custom dialer or TLS config and still attempt HTTP/2
	// upgrades, set this to true.
	ForceAttemptHTTP2 bool

	*ResponseOptions

	Debugf func(format string, v ...interface{})
	// contains filtered or unexported fields
}

Transport is an implementation of http.RoundTripper that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).

By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport's CloseIdleConnections method and the MaxIdleConnsPerHost and DisableKeepAlives fields.

Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.

A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.

Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The DefaultTransport supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2.

Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by RoundTrip. To see the ignored 1xx responses, use the httptrace trace package's ClientTrace.Got1xxResponse.

Transport only retries a request upon encountering a network error if the request is idempotent and either has no body or has its Request.GetBody defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire.

func (*Transport) CancelRequest deprecated

func (t *Transport) CancelRequest(req *http.Request)

CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after RoundTrip has returned.

Deprecated: Use Request.WithContext to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests.

func (*Transport) Clone

func (t *Transport) Clone() *Transport

Clone returns a deep copy of t's exported fields.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

func (*Transport) DisableDump

func (t *Transport) DisableDump()

DisableDump disables the dump.

func (*Transport) EnableDump

func (t *Transport) EnableDump(opt *DumpOptions)

EnableDump enables the dump for all requests with specified dump options.

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt http.RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the RoundTrip itself for that one request, as if the protocol were not registered.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)

RoundTrip implements the RoundTripper interface.

For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.

Directories

Path Synopsis
Package internal contains HTTP internals shared by net/http and net/http/httputil.
Package internal contains HTTP internals shared by net/http and net/http/httputil.
godebug
Package godebug parses the GODEBUG environment variable.
Package godebug parses the GODEBUG environment variable.
testcert
Package testcert contains a test-only localhost certificate.
Package testcert contains a test-only localhost certificate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL