grequest

package module
v0.0.0-...-de6557b Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2020 License: Apache-2.0 Imports: 12 Imported by: 0

README

There are three objects in grequest:

  1. Client: is http.Client, different requests can use the same http.Client, or not, it depends on your
  2. Request: have http.Request, URL, method, cookie, RetryConfig, etc.
  3. Result: have http.Response, error, retry log, cost time, etc.

Features

  • Method chaining
  • Reuse http.Client: means you can use the connection pool of http.Client
  • Set: set header, method, cookie, etc.
  • JSON: Post JSON request, receive JSON response
  • Timeout: set request timeout
  • Retry: set retry HTTP status, retry times and retry interval
  • BasicAuth: set authentication header

How to use grequest

see request_test.go for more examples.

GET

Example 1
//new a client with 1s timeout
client := NewClient(time.Second)  

// send request
resp, body, err := NewRequest(client).Get("https://github.com/").send()
Example 2
resp, body, err := NewRequest(client).
    SetHeader("TestHeader", "header").  //set a new header 
    AddHeader("TestHeader", "header2").  //add(not replace) a header which already exist 
    SetRetry(1, time.Millisecond*50, nil, 500, 504).  //using retry, try again 50ms later when last request return a http status between 500 and 504
    DisableKeepAlive().
    Get("http://test.com"). 
    Send().
    Response()

POST

type Req struct {
  Name string
  Age  int
}
respJson := make(map[string]string, 0)
resp, body, err := NewRequest(client).
    SetRetry(1, time.Millisecond*50, []int{500,502}, -1, -1).  //using retry,try again 50ms later when last request return a http status is 500 or 502
    Post("http://test.com").
    SendJson(&Req{Name:"test", Age:10}).
    JsonTo(respJson)

Using a global default client

//new a default client with 3s timeout
SetDefaultClient(NewClient(time.Second * 3))

// send request using default client
resp, body, err := NewRequest(DefaultClient()).Get("http://test.com").send()

Documentation

Index

Constants

View Source
const (
	POST    = "POST"
	GET     = "GET"
	HEAD    = "HEAD"
	PUT     = "PUT"
	DELETE  = "DELETE"
	PATCH   = "PATCH"
	OPTIONS = "OPTIONS"

	TypeJSON       = "json"
	TypeXML        = "xml"
	TypeUrlencoded = "urlencoded"
	TypeForm       = "form"
	TypeFormData   = "form-data"
	TypeHTML       = "html"
	TypeText       = "text"
	TypeMultipart  = "multipart"
)

Variables

View Source
var Types = map[string]string{
	TypeJSON:       "application/json",
	TypeXML:        "application/xml",
	TypeForm:       "application/x-www-form-urlencoded",
	TypeFormData:   "application/x-www-form-urlencoded",
	TypeUrlencoded: "application/x-www-form-urlencoded",
	TypeHTML:       "text/html",
	TypeText:       "text/plain",
	TypeMultipart:  "multipart/form-data",
}

Functions

func DefaultClient

func DefaultClient() *http.Client

func NewClient

func NewClient(timeout time.Duration) *http.Client

func NowUnix

func NowUnix() int64

func SetDefaultClient

func SetDefaultClient(client *http.Client)

Types

type File

type File struct {
	Abs     string
	Name    string
	Field   string
	Content []byte
}

send file(s)

type Request

type Request struct {
	Client  *http.Client
	Url     string
	Method  string
	Header  http.Header
	Cookies []*http.Cookie

	FormData         url.Values
	QueryData        url.Values
	TargetType       string
	ForceType        string
	BasicAuth        struct{ Username, Password string }
	IsKeepAlive      bool
	ExpectRespStatus int
	RetryCfg         *RetryConfig
}

A Request is a object storing all request data for client.

func NewRequest

func NewRequest(client *http.Client) *Request

Used to create a new Request object.

func (*Request) AddCookie

func (r *Request) AddCookie(c *http.Cookie) *Request

cookie

func (*Request) AddCookies

func (r *Request) AddCookies(cookies []*http.Cookie) *Request

func (*Request) AddHeader

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

func (*Request) AddQueryParam

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

func (*Request) CustomMethod

func (r *Request) CustomMethod(method, targetUrl string) *Request

Just a wrapper to initialize Request instance by method string

func (*Request) Delete

func (r *Request) Delete(targetUrl string) *Request

func (*Request) DisableKeepAlive

func (r *Request) DisableKeepAlive() *Request

func (*Request) EnableKeepAlive

func (r *Request) EnableKeepAlive() *Request

func (*Request) Get

func (r *Request) Get(targetUrl string) *Request

func (*Request) Head

func (r *Request) Head(targetUrl string) *Request

func (*Request) Options

func (r *Request) Options(targetUrl string) *Request

func (*Request) Patch

func (r *Request) Patch(targetUrl string) *Request

func (*Request) Post

func (r *Request) Post(targetUrl string) *Request

func (*Request) Put

func (r *Request) Put(targetUrl string) *Request

func (*Request) Send

func (r *Request) Send() *Result

send a request without 'body'

func (*Request) SendBytes

func (r *Request) SendBytes(body []byte) *Result

func (*Request) SendFile

func (r *Request) SendFile(absFile, fileName, fieldName string, fileContent []byte) *Result

send fileContent if it's not nil or read and send absFile

func (*Request) SendFiles

func (r *Request) SendFiles(files []*File) *Result

func (*Request) SendForm

func (r *Request) SendForm(content interface{}) *Result

send form

func (*Request) SendJson

func (r *Request) SendJson(content interface{}) *Result

send json

func (*Request) SendString

func (r *Request) SendString(body string) *Result

send raw

func (*Request) SetBasicAuth

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

func (*Request) SetDefaultRetry

func (r *Request) SetDefaultRetry() *Request

func (*Request) SetExpectRespStatus

func (r *Request) SetExpectRespStatus(httpStatus int) *Request

response set a http status of response which you expected

func (*Request) SetHeader

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

header

func (*Request) SetQueryMap

func (r *Request) SetQueryMap(content map[string]string) *Request

Query

func (*Request) SetQueryParam

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

func (*Request) SetRetry

func (r *Request) SetRetry(maxRetry int, interval time.Duration, status []int, statusBegin int, statusEnd int) *Request

retry

func (*Request) SetRetryConfig

func (r *Request) SetRetryConfig(config *RetryConfig) *Request

type Result

type Result struct {
	Resp          *http.Response
	Body          []byte
	Err           error
	Logs          []*TraceLog
	TotalCostTime int64
	// contains filtered or unexported fields
}

func (*Result) JsonTo

func (r *Result) JsonTo(v interface{}) (*http.Response, []byte, error)

func (*Result) LogInfo

func (r *Result) LogInfo() *Result

func (*Result) Response

func (r *Result) Response() (*http.Response, []byte, error)

type RetryConfig

type RetryConfig struct {
	Status      map[int]struct{}
	StatusBegin int
	StatusEnd   int
	Interval    time.Duration
	MaxRetry    int
	Counter     int
}

func NewRetryConfig

func NewRetryConfig(maxRetry int, interval time.Duration, status []int, statusBegin int, statusEnd int) *RetryConfig

type TraceLog

type TraceLog struct {
	RetryId    int
	CostTimeMs int64
	Status     int
	Body       []byte
	Err        error
}

Jump to

Keyboard shortcuts

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