package module
v1.0.35 Latest Latest

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

Go to latest
Published: May 11, 2024 License: Apache-2.0 Imports: 28 Imported by: 1



license Requests is an HTTP library like python requests.


go get -u


For more examples, refer to examples/post and all examples


package main
import (

func main(){
    var json map[string]interface{}
    params := requests.Params{"name": "ahuigo", "page":"1"}
    resp, err := requests.Get("", params)
    if err != nil {
        for k, v := range json {
            fmt.Println(k, v)


Debug Mode

Refer to

session := requests.R()
resp, err := session.SetDebug().Post(
        "file1": "/",
        "file2": "/version",
/* Output:
 curl -X POST -F 'file1=@/' -F 'file2=@/version'
Post params
// Post params
func TestPostParams(t *testing.T) {
    println("Test POST: post params")
    data := requests.Params{
        "name": "ahuigo",
    resp, err := requests.Post("", data)
    if err == nil {
Post application/x-www-form-urlencoded
// Post Form UrlEncoded data: application/x-www-form-urlencoded
func TestPostFormUrlEncode(t *testing.T) {
    resp, err := requests.Post(
            "name": "ahuigo",
    if err != nil {
    var data = struct {
        Form struct {
            Name string
    if data.Form.Name != "ahuigo" {
        t.Error("invalid response body:", resp.Text())
Post multipart/form-data
// Test POST:  multipart/form-data; boundary=....
func TestPostFormData(t *testing.T) {
    resp, err := requests.Post(
            "name": "ahuigo",
    if err != nil {
    var data = struct {
        Form struct {
            Name string
    if data.Form.Name != "ahuigo" {
        t.Error("invalid response body:", resp.Text())
Post Json: application/json
func TestPostJson(t *testing.T) {
	// You can also use `json := requests.Jsoni(anyTypeData)`
    json := requests.Json{
        "key": "value",
    resp, err := requests.Post("", json)
    if err == nil {
Post Raw text/plain
func TestRawString(t *testing.T) {
    println("Test POST: post data and json")
    rawText := "raw data: Hi, Jack!"
    resp, err := requests.Post(
        requests.Header{"Content-Type": "text/plain"},
    if err == nil {

An example about post both file and form data:

// curl "" -F 'file1=@./go.mod' -F 'file2=@./version' -F 'name=alex'
path, _ := os.Getwd()
session := requests.R()

resp, err := session.SetDebug().Post(
        "file1": path + "/go.mod",
        "file2": path + "/version",
		"name": "alex",
if err == nil {

Session Support

// 0. Make a session
session := r.R()

// 1. First, set cookies: count=100
var data struct {
	Cookies struct {
		Count string `json:"count"`

// 2. Second, get cookies
resp, err := session.Get("")
if err == nil {
    if data.Cookies.Count!="100"{
        t.Fatal("Failed to get valid cookies: "+resp.Text())

Warning: Session is not safe in multi goroutines. You can not do as following:

// Bad! Do not call session in in multi goroutine!!!!!
session := requests.R()

// goroutine 1
go func(){

// goroutine 2
go func(){

Request Options

session := Requests.R()
Set Authentication
session := requests.R()
resp,_ := session.Get("",requests.Auth{"asmcos","password...."})
cookie1 := http.Cookie{Name: "cookie_name", Value: "cookie_value"}
Set header
func TestGetParamsHeaders(t *testing.T) {
    println("Test Get: custom header and params")
        requests.Header{"Referer": ""},
        requests.Params{"page": "1", "size": "20"},
        requests.Params{"name": "ahuio"},

func TestGetParamsHeaders2(t *testing.T) {
    session := requests.R()
    session.SetHeader("accept-encoding", "gzip, deflate, br")
        requests.Params{"page": "1", "size": "20"},
        requests.Params{"name": "ahuio"},

func TestResponseHeader(t *testing.T) {
    resp, _ := requests.Get("")

two or more headers ...

headers1 := requests.Header{"Referer": ""},
resp,_ = session.Get(


Fetch Response Body

fmt.Println(resp.Text())    // string
fmt.Println(resp.Body())    //[]byte
Fetch Response Cookies

resp,_ = session.Get("")
coo := resp.Cookies()
for _, c:= range coo{
Response examples
func TestResponse(t *testing.T) {
    resp, _ := requests.Get("")
    fmt.Println("Status Code:", resp.StatusCode())
    fmt.Println("Time:", resp.Time())
    fmt.Println("Size:", resp.Size())
    for key, value := range resp.Header() {
        fmt.Println(key, "=", value)
    for i, cookie := range resp.Cookies() {
        fmt.Printf("cookie%d: name:%s value:%s\n", i, cookie.Name, cookie.Value)


Build Request

req, err := r.BuildRequest("post", "", r.Json{
	"age": 1,
if err != nil {
body, _ := ioutil.ReadAll(req.Body)
expectedBody := `{"age":1}`
if string(body) != expectedBody {
	t.Fatal("Failed to build request")

Generate curl shell command

req, _ := requests.BuildRequest("post", "", requests.Json{
	"age": 1,
curl := requests.BuildCurlRequest(req)
if !regexp.MustCompile(`^curl -X POST .+ '\?q=curl&v=1'`).MatchString(curl) {
	t.Fatal(`bad curl cmd: ` + curl)

Retry request

r := requests.R().
	SetRetryCondition(func(resp *requests.Response, err error) bool {
		if err != nil {
			return true
		var json map[string]interface{}
		return json["status"]!="ok"

Feature Support

  • Set headers, params, body, json, ....
  • Multipart File Uploads
  • R-seesion with Cookie Persistence
  • Proxy
    • Http Proxy
    • [] Socks5 Proxy
  • Authentication
  • JSON
  • Chunked Requests
  • Debug Mode
    • Support Curl Dump
  • SetTimeout
  • Retry
  • [] Support traceInfo(like resty's clientTrace and gout)
  • [] Support http stream and callback(notParseResponse)
  • [] Remove Global Setting
  • [] Support http2
  • [] Support retry
  • [] Support connection pool
  • [] Middleware support?


This project is inspired by

Great thanks to it :).



Copyright (c) 2015-2021 Jeevanandam M (, All rights reserved. resty source code and usage is governed by a MIT style license that can be found in the LICENSE file.



This section is empty.


View Source
var VERSION string = "v0.0.0"


func Backoff added in v1.0.24

func Backoff(operation func() (*Response, error), options ...Option) error

Backoff retries with increasing timeout duration up until X amount of retries (Default is 3 attempts, Override with option Retries(n))

func BuildCurlRequest added in v0.1.17

func BuildCurlRequest(req *http.Request, args ...interface{}) (curl string)

func BuildRequest

func BuildRequest(method string, origurl string, args ...interface{}) (req *http.Request, err error)

BuildRequest -

func IoCaptureOutput added in v1.0.12

func IoCaptureOutput(f func()) string

func NewHttpClient added in v1.0.9

func NewHttpClient() *http.Client

func SetRespHandler

func SetRespHandler(fn func(*Response) error)


type Auth

type Auth []string

Auth - {username,password}

type ContentType added in v0.2.0

type ContentType string

type AnyData interface{} // for AnyData

const (
	ContentTypeNone       ContentType = ""
	ContentTypeFormEncode ContentType = "application/x-www-form-urlencoded"
	ContentTypeFormData   ContentType = "multipart/form-data"
	ContentTypeJson       ContentType = "application/json"
	ContentTypePlain      ContentType = "text/plain"

type Datas

type Datas map[string]string // for post form urlencode

type Files

type Files map[string]string // name ,filename

type FormData added in v0.2.0

type FormData map[string]string // for post multipart/form-data
type Header map[string]string

type Json

type Json map[string]interface{} // for Json map

type Jsoni added in v1.0.1

type Jsoni interface{} // for Json interface

type OnRetryFunc added in v1.0.24

type OnRetryFunc func(*Response, error)

OnRetryFunc is for side-effecting functions triggered on retry

type Option added in v1.0.24

type Option func(*Options)

Option is to create convenient retry options like wait time, max retries, etc.

func MaxWaitTime added in v1.0.24

func MaxWaitTime(value time.Duration) Option

MaxWaitTime sets the max wait time to sleep between requests

func Retries added in v1.0.24

func Retries(value int) Option

Retries sets the max number of retries

func RetryConditions added in v1.0.24

func RetryConditions(conditions []RetryConditionFunc) Option

RetryConditions sets the conditions that will be checked for retry.

func WaitTime added in v1.0.24

func WaitTime(value time.Duration) Option

WaitTime sets the default wait time to sleep between requests

type Options added in v1.0.24

type Options struct {
	// contains filtered or unexported fields

Options struct is used to hold retry settings.

type Params

type Params map[string]string

type ParamsArray added in v1.0.21

type ParamsArray map[string][]string

type Response

type Response struct {
	R       *http.Response
	Attempt int

	TraceInfo *TraceInfo
	// contains filtered or unexported fields

func BuildResponse added in v1.0.9

func BuildResponse(response *http.Response) *Response

func Delete

func Delete(origurl string, args ...interface{}) (resp *Response, err error)


func Get

func Get(origurl string, args ...interface{}) (resp *Response, err error)


func Patch

func Patch(origurl string, args ...interface{}) (resp *Response, err error)


func Post

func Post(origurl string, args ...interface{}) (resp *Response, err error)

func Put

func Put(origurl string, args ...interface{}) (resp *Response, err error)


func (*Response) Body added in v1.0.8

func (resp *Response) Body() []byte

func (*Response) Cookies

func (resp *Response) Cookies() (cookies []*http.Cookie)

func (*Response) GetCookie added in v1.0.11

func (resp *Response) GetCookie(key string) (val string)

func (*Response) GetDumpCurl added in v1.0.13

func (resp *Response) GetDumpCurl() string

func (*Response) GetDumpResponse added in v1.0.13

func (resp *Response) GetDumpResponse() string

func (*Response) GetReq added in v1.0.13

func (resp *Response) GetReq() (req *http.Request)

func (*Response) HasCookie added in v1.0.11

func (resp *Response) HasCookie(key string) (exists bool)

func (*Response) Header added in v1.0.8

func (resp *Response) Header() http.Header

func (*Response) Json

func (resp *Response) Json(v interface{}) error

func (*Response) RaiseForStatus added in v1.0.3

func (resp *Response) RaiseForStatus() (code int, err error)

func (*Response) ResponseDebug

func (resp *Response) ResponseDebug()

func (*Response) SaveFile

func (resp *Response) SaveFile(filename string) error

func (*Response) SetClientReq added in v1.0.10

func (resp *Response) SetClientReq(req *http.Request, client *http.Client) *Response

func (*Response) SetDoNotCloseBody added in v1.0.35

func (resp *Response) SetDoNotCloseBody() *Response

func (*Response) SetStartEndTime added in v1.0.9

func (resp *Response) SetStartEndTime(start, end time.Time) *Response

func (*Response) Size added in v1.0.8

func (resp *Response) Size() int

func (*Response) StatusCode added in v1.0.3

func (resp *Response) StatusCode() (code int)

func (*Response) Text

func (resp *Response) Text() string

func (*Response) Time added in v1.0.8

func (resp *Response) Time() time.Duration

type RetryConditionFunc added in v1.0.24

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc type is for retry condition function input: non-nil Response OR request execution error

type Session

type Session struct {
	Client *http.Client
	// contains filtered or unexported fields

func NewSession added in v1.0.4

func NewSession() *Session

New request session

func R added in v1.0.8

func R() *Session

New request session @params method GET|POST|PUT|DELETE|PATCH

func (*Session) BuildRequest

func (session *Session) BuildRequest(method, origurl string, args ...interface{}) (*http.Request, error)


func (*Session) ClearCookies

func (session *Session) ClearCookies()

func (*Session) Clone added in v1.0.2

func (session *Session) Clone() *Session

func (*Session) Close

func (session *Session) Close()

func (*Session) DelGlobalHeader added in v1.0.11

func (session *Session) DelGlobalHeader(key string) *Session

Del global header

func (*Session) Delete

func (session *Session) Delete(origurl string, args ...interface{}) (resp *Response, err error)

func (*Session) DisableDebug added in v1.0.8

func (session *Session) DisableDebug() *Session

func (*Session) Get

func (session *Session) Get(origurl string, args ...interface{}) (resp *Response, err error)

func (*Session) GetGlobalHeader added in v1.0.11

func (session *Session) GetGlobalHeader() map[string]string

Get global header

func (*Session) GetTransport added in v1.0.30

func (session *Session) GetTransport() *http.Transport

func (*Session) Patch

func (session *Session) Patch(origurl string, args ...interface{}) (resp *Response, err error)

func (*Session) Post

func (session *Session) Post(origurl string, args ...interface{}) (resp *Response, err error)

func (*Session) Put

func (session *Session) Put(origurl string, args ...interface{}) (resp *Response, err error)

func (*Session) RequestDebug

func (session *Session) RequestDebug() string

func (*Session) Run

func (session *Session) Run(origurl string, args ...interface{}) (resp *Response, err error)


func (*Session) SetContext added in v1.0.29

func (session *Session) SetContext(ctx context.Context) *Session

func (*Session) SetCookie

func (session *Session) SetCookie(cookie *http.Cookie) *Session

cookies only save to Client.Jar session.initCookies is temporary

func (*Session) SetDebug

func (session *Session) SetDebug() *Session

func (*Session) SetDebugBody added in v1.0.12

func (session *Session) SetDebugBody() *Session

func (*Session) SetDoNotCloseBody added in v1.0.35

func (session *Session) SetDoNotCloseBody(flag bool) *Session

func (*Session) SetGlobalHeader added in v1.0.11

func (session *Session) SetGlobalHeader(key, value string) *Session

Set global header

func (*Session) SetHeader

func (session *Session) SetHeader(key, value string) *Session


func (*Session) SetMethod

func (session *Session) SetMethod(method string) *Session


func (*Session) SetProxy added in v1.0.29

func (session *Session) SetProxy(proxyurl string) *Session

func (*Session) SetRespHandler

func (session *Session) SetRespHandler(fn func(*Response) error) *Session

func (*Session) SetRetryCondition added in v1.0.24

func (session *Session) SetRetryCondition(fn func(*Response, error) bool) *Session

func (*Session) SetRetryCount added in v1.0.24

func (session *Session) SetRetryCount(count int) *Session

func (*Session) SetRetryWaitTime added in v1.0.24

func (session *Session) SetRetryWaitTime(waitTime time.Duration) *Session

func (*Session) SetRootCertificate added in v1.0.33

func (session *Session) SetRootCertificate(caPemPath string) *Session

In generally, you could SystemCertPool instead of NewCertPool to keep existing certs.

func (*Session) SetTimeout

func (session *Session) SetTimeout(n time.Duration) *Session

set timeout s = second

func (*Session) SetTransport added in v1.0.30

func (session *Session) SetTransport(tsp *http.Transport) *Session

func (*Session) SkipSsl added in v1.0.25

func (session *Session) SkipSsl(v bool) *Session


type TraceInfo added in v1.0.29

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

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

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

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

	// ServerTime is a duration that server took to respond first byte.
	ServerTime 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

	// RequestAttempt is to represent the request attempt made during a Resty
	// request execution flow, including retry count.
	RequestAttempt int

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

TraceInfo struct is used provide request trace info such as DNS lookup duration, Connection obtain duration, Server processing duration, etc.

Since v2.0.0


Path Synopsis
Package shellescape provides the shellescape.Quote to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells.
Package shellescape provides the shellescape.Quote to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells.

Jump to

Keyboard shortcuts

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