quick

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2022 License: MIT Imports: 32 Imported by: 0

README

Quick

GoDoc

Simple and efficient HTTP request library

简单高效的Http请求库

examples

package main

import (
    "fmt"
    "github.com/telanflow/quick"
    "net/http"
)

func main() {
    // quick.Post("example.com")
    // quick.PostFormData("example.com")
    // quick.Put("example.com")
    // quick.Head("example.com")
    // quick.Delete("example.com")
    // quick.Patch("example.com")
    // quick.Options("example.com")
    // quick.Trace("example.com")

    // https ssl skip verify 取消https验证
    quick.InsecureSkipVerify(true)

    // set header
    quick.SetHeader(http.Header{
        "Context-Type": []string{"text/html"},
    })
    // set UserAgent to request
    quick.SetHeaderSingle("User-Agent", "A go request libraries for quick")
    quick.SetUserAgent("A go request libraries for quick")
    
    // You should init it by using NewCookiesWithString like this:
    // 	cookies := quick.NewCookiesWithString(
    //		"key1=value1; key2=value2; key3=value3"
    // 	)
    // Note: param is cookie string
    cookies := quick.NewCookiesWithString("sessionid=11111")
    
    // request
    resp, err := quick.Get(
        "http://example.com?bb=1", 
        quick.OptionQueryString("name=quick&aa=11"),   // set Get params   eg. "example.com?bb=1&name=quick&aa=11"
        quick.OptionHeaderSingle("User-Agent", ""),    // set http header
        quick.OptionHeader(http.Header{}),             // set http header  eg. http.Header || map[string]string || []string
        quick.OptionRedirectNum(10),                   // set redirect num
        quick.OptionCookies(cookies),                  // set cookies to request
        // quick.OptionProxy("http://127.0.0.1:8080"), // set proxy address
        // quick.OptionBody(""),                       // POST body
        // quick.OptionBasicAuth("username", "password"), // HTTP Basic Authentication
        // ... quick.Option
    )
    if err != nil {
        panic(err)
    }

    fmt.Println(resp)
}
Session (会话)

Request based session

所有Request都基于session(http.Client)

func main() {
    // cookieJar
    cookieJar, err := quick.NewCookieJar()
    if err != nil {
        panic(err)
    }
    
    // quick use default global session
    // create session
    session := quick.NewSession()
    // https ssl skip verify 取消https验证
    session.InsecureSkipVerify(true)
    // set cookieJar
    session.SetCookieJar(cookieJar) 
    resp, err := session.Get("http://example.com")
    if err != nil {
        panic(err)
    }
    //resp.Status       e.g. "200 OK"
    //resp.StatusCode   e.g. 200
    //... 
    fmt.Println(resp)
}

Other example:

func main() {
    // new Request
    req := quick.NewRequest().SetUrl("http://example.com").SetMethod(http.MethodGet)

    // send Request
    session := quick.NewSession()
	session.EnableTrace() // trace
    resp, err := session.Suck(
        req, 
        quick.OptionHeaderSingle("User-Agent", ""), // set http header
        // ... quick.Option
    )
    if err != nil {
        panic(err)
    }

    // resp.Status       e.g. "200 OK"
    // resp.StatusCode   e.g. 200
    // ...
    // 
    // TraceInfo:
    //      DNSLookup: 4ms
    //      ConnTime: 1230ms
    //      TCPConnTime: 405ms
    //      TLSHandshake: 819ms
    //      ServerTime: 299ms
    fmt.Println(resp)
    fmt.Println(resp.TraceInfo())
}

Middleware(中间件)

func main() {
    // new Request
    req := quick.NewRequest().SetUrl("http://example.com").SetMethod(http.MethodGet)

    // create session
    session := quick.NewSession()

    // use middleware
    session.Use(
        // middleware 1
        func(r *http.Request) {
            log.Printf(
                "Middleware: %v RedirectNum: %v Proxy: %v \n",
                r.URL,
                r.Context().Value(quick.ContextRedirectNumKey),
                r.Context().Value(quick.ContextProxyKey),
            )
        },
        // middleware 2
        func(r *http.Request) {
            log.Printf(
                "Middleware2: %v RedirectNum: %v Proxy: %v \n",
                r.URL,
                r.Context().Value(quick.ContextRedirectNumKey),
                r.Context().Value(quick.ContextProxyKey),
            )
        },
    )

    // send Request
    resp, err := session.Suck(
        req, 
        quick.OptionHeaderSingle("User-Agent", ""), // set http header
        // ... quick.Option
    )
    if err != nil {
        panic(err)
    }

    //resp.Status       e.g. "200 OK"
    //resp.StatusCode   e.g. 200
    //... 
    fmt.Println(resp)
}

License

MIT

Documentation

Index

Constants

View Source
const (
	// default redirect num
	DefaultRedirectNum = 10
	// request context redirect num key name
	ContextRedirectNumKey = "redirectNum"
)
View Source
const ContextProxyKey = "proxy"

request context proxy key name

Variables

View Source
var (
	ErrRequestBody = errors.New("request encode can`t coexists with PostForm")
	ErrTimeout     = errors.New("reqeust timeout")
)

Functions

func CopyHeader

func CopyHeader(h http.Header) http.Header

CopyHeader copy headers

func CopyURL

func CopyURL(u *url.URL) (URL *url.URL, err error)

CopyURL copy a new url.URL

func Download

func Download(rawurl string, toFile string) error

Download download file to save hard disk

func GetHeader

func GetHeader() http.Header

GetHeader get global header

func GetHeaderSingle

func GetHeaderSingle(key string) string

GetHeaderSingle get global header single

func GetProxyURL

func GetProxyURL() *url.URL

GetProxyURL get session global proxy url

func GetProxyUrl

func GetProxyUrl() string

GetProxyUrl get session global proxy url

func GetUserAgent

func GetUserAgent() string

GetUserAgent get global user-agent

func MergeHeaders

func MergeHeaders(h1, h2 http.Header) http.Header

MergeHeaders merge Request headers and Session Headers. Request has higher priority.

func MergeQueryString

func MergeQueryString(parsedURL *url.URL, parsedQuery string) (*url.URL, error)

MergeQueryString Get request merge url and query string encode.

func NewCookieJar

func NewCookieJar() (http.CookieJar, error)

create a cookieJar

func ReplaceQueryString

func ReplaceQueryString(parsedURL *url.URL, parsedQuery string) (*url.URL, error)

ReplaceQueryString Get request replace url and query string encode.

func WrapErr

func WrapErr(err error, msg string) error

WrapErr will wrap a error with some information: filename, line, time and some message.

func WrapErrf

func WrapErrf(err error, format string, args ...interface{}) error

WrapErr will wrap a error with some information: filename, line, time and some message. You can format message of error.

Types

type Cookies

type Cookies = []*http.Cookie

defined []http.Cookie alias Cookies

func NewCookiesWithString

func NewCookiesWithString(rawstr string) Cookies

You should init it by using NewCookiesWithString like this:

cookies := quick.NewCookiesWithString(
	"key1=value1; key2=value2; key3=value3"
)

Note: param is cookie string

type Error

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

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type HandlerFunc

type HandlerFunc func(r *http.Request)

type Logger added in v0.4.0

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

Logger interface is to abstract the logging from quick. Gives control to the quick users, choice of the logger.

type OptionFunc

type OptionFunc func(*Request)

OptionFunc request option func

func OptionBasicAuth

func OptionBasicAuth(username, password string) OptionFunc

OptionBasicAuth HTTP Basic Authentication

func OptionBody

func OptionBody(v interface{}) OptionFunc

OptionBody request body for post

func OptionBodyFormData

func OptionBodyFormData(v interface{}) OptionFunc

OptionBodyFormData request body for post (FormData)

func OptionBodyJSON added in v0.4.1

func OptionBodyJSON(v interface{}) OptionFunc

OptionBodyJSON request body for post

func OptionBodyXML added in v0.4.1

func OptionBodyXML(v interface{}) OptionFunc

OptionBodyXML request body for post

func OptionBodyXWwwFormUrlencoded added in v0.4.1

func OptionBodyXWwwFormUrlencoded(v interface{}) OptionFunc

OptionBodyXWwwFormUrlencoded set request body x-www-form-urlencoded

func OptionCookies

func OptionCookies(cookies Cookies) OptionFunc

OptionCookies set cookies to request

func OptionHeader

func OptionHeader(v interface{}) OptionFunc

OptionHeader set request header

func OptionHeaderSingle

func OptionHeaderSingle(k, v string) OptionFunc

OptionHeaderSingle set an http header to request

func OptionProxy

func OptionProxy(v interface{}) OptionFunc

OptionProxy set proxy for request

func OptionQueryString

func OptionQueryString(v interface{}) OptionFunc

OptionQueryString request query string for get

func OptionRedirectNum

func OptionRedirectNum(num int) OptionFunc

OptionRedirectNum set redirect num to request

func OptionTimeout

func OptionTimeout(v time.Duration) OptionFunc

OptionTimeout set timeout to request

type RedirectError

type RedirectError struct {
	RedirectNum int
}

func (*RedirectError) Error

func (e *RedirectError) Error() string

type Request

type Request struct {
	Id          uint64
	URL         *url.URL
	Method      string
	Header      http.Header   // request headers
	Body        io.Reader     // request encode
	RedirectNum int           // Number of redirects requested. default 5
	Timeout     time.Duration // request timeout
	Proxy       *url.URL      // request proxy url
	Cookies     Cookies       // request cookies
	// contains filtered or unexported fields
}

Request http request payload

func ConvertHttpRequest

func ConvertHttpRequest(r *http.Request) *Request

ConvertHttpRequest convert http.Request To Request

func NewRequest

func NewRequest() *Request

NewRequest create a request instance

func NewRequestWithContext

func NewRequestWithContext(ctx context.Context) *Request

NewRequestWithContext create a request instance with context.Context

func (*Request) BasicAuth

func (req *Request) BasicAuth() (username, password string, ok bool)

BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

func (*Request) Context

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

Context get context.Context for Request

func (*Request) Copy

func (req *Request) Copy() *Request

Copy copy a new request

func (*Request) DisableTrace added in v0.4.0

func (req *Request) DisableTrace() *Request

DisableTrace method disables the Quick client trace. Refer to `Request.EnableTrace`.

Since v0.4.0

func (*Request) EnableTrace added in v0.4.0

func (req *Request) EnableTrace() *Request

EnableTrace method enables trace for the current request using `httptrace.ClientTrace` and provides insights.

resp, err := quick.EnableTrace().Get("https://httpbin.org/get")
fmt.Println("Error:", err)
fmt.Println("Trace Info:", resp.TraceInfo())

See `Request.EnableTrace` available too to get trace info for all requests.

Since v0.4.0

func (*Request) GetHeader

func (req *Request) GetHeader() http.Header

GetHeader get request header

func (*Request) GetHeaderSingle

func (req *Request) GetHeaderSingle(key string) string

GetHeaderSingle get request header single

func (*Request) GetMethod

func (req *Request) GetMethod() string

GetMethod get request method

func (*Request) GetProxyURL

func (req *Request) GetProxyURL() *url.URL

GetProxyURL get proxy url.URL for this request

func (*Request) GetProxyUrl

func (req *Request) GetProxyUrl() string

GetProxyUrl get proxy url for this request

func (*Request) GetTimeout

func (req *Request) GetTimeout() time.Duration

GetTimeout get request timeout

func (*Request) GetURL

func (req *Request) GetURL() *url.URL

GetURL get request url

func (*Request) GetUrl

func (req *Request) GetUrl() string

GetUrl get request url

func (*Request) GetUserAgent

func (req *Request) GetUserAgent() string

GetUserAgent get request user-agent

func (*Request) SetBasicAuth

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

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with url.QueryEscape.

func (*Request) SetBody

func (req *Request) SetBody(params interface{}) *Request

SetBody set POST body to request

func (*Request) SetBodyFormData

func (req *Request) SetBodyFormData(params interface{}) *Request

SetBodyFormData set POST body (FormData) to request

func (*Request) SetBodyJson

func (req *Request) SetBodyJson(params interface{}) *Request

SetBodyJson set POST body (RAW) to request

func (*Request) SetBodyXML added in v0.4.1

func (req *Request) SetBodyXML(params interface{}) *Request

SetBodyXML set POST body (RAW) to request

func (*Request) SetBodyXWwwFormUrlencoded

func (req *Request) SetBodyXWwwFormUrlencoded(params interface{}) *Request

SetBodyXWwwFormUrlencoded set request body x-www-form-urlencoded

func (*Request) SetCharset

func (req *Request) SetCharset(charset string) *Request

SetCharset set request charset

func (*Request) SetCookies

func (req *Request) SetCookies(cookies Cookies) *Request

SetCookies set cookies to request sample:

quick.SetCookies(
	quick.NewCookiesWithString("key1=value1; key2=value2; key3=value3")
)

func (*Request) SetHeader

func (req *Request) SetHeader(header http.Header) *Request

SetHeader set request header

func (*Request) SetHeaderSingle

func (req *Request) SetHeaderSingle(key, val string) *Request

SetHeaderSingle set request header single

func (*Request) SetHeaders

func (req *Request) SetHeaders(header http.Header) *Request

SetHeaders merge request origin header and header

func (*Request) SetHost

func (req *Request) SetHost(host string) *Request

SetHost custom request host field GET /index HTTP/1.1 Host: domain ....

func (*Request) SetMethod

func (req *Request) SetMethod(method string) *Request

SetMethod set request method

func (*Request) SetProxyURL

func (req *Request) SetProxyURL(u *url.URL) *Request

SetProxyURL set the proxy url for this request

func (*Request) SetProxyUrl

func (req *Request) SetProxyUrl(rawurl string) *Request

SetProxyUrl set the proxy for this request eg. "http://127.0.0.1:8080" "http://username:password@127.0.0.1:8080"

func (*Request) SetQueryString

func (req *Request) SetQueryString(params interface{}) *Request

SetQueryString set GET parameters to request

func (*Request) SetReferer

func (req *Request) SetReferer(referer string) *Request

SetReferer set request referer

func (*Request) SetTimeout

func (req *Request) SetTimeout(t time.Duration) *Request

SetTimeout set request timeout

func (*Request) SetURL

func (req *Request) SetURL(u *url.URL) *Request

SetURL set request url

func (*Request) SetUrl

func (req *Request) SetUrl(rawurl string) *Request

SetUrl set request url

func (*Request) SetUserAgent

func (req *Request) SetUserAgent(ua string) *Request

SetUserAgent set request user-agent

func (*Request) TraceInfo added in v0.4.0

func (req *Request) TraceInfo() TraceInfo

TraceInfo method returns the trace info for the request. If either the Client or Request EnableTrace function has not been called prior to the request being made, an empty TraceInfo object will be returned.

Since v0.4.0

func (*Request) WithContext

func (req *Request) WithContext(ctx context.Context) *Request

WithContext with context.Context for Request

type Response

type Response struct {
	RequestId        uint64 // request id
	HttpRequest      *http.Request
	Status           string // e.g. "200 OK"
	StatusCode       int    // e.g. 200
	Proto            string // e.g. "HTTP/1.0"
	ProtoMajor       int    // e.g. 1
	ProtoMinor       int    // e.g. 0
	Header           http.Header
	Body             *bytes.Buffer
	ContentLength    int64
	ExecTime         time.Duration // request exec time
	TLS              *tls.ConnectionState
	TransferEncoding []string
	Encoding         encoding.Encoding // Response body encoding
	// contains filtered or unexported fields
}

func BuildResponse

func BuildResponse(resp *http.Response) (*Response, error)

func Connect

func Connect(rawurl string, ops ...OptionFunc) (*Response, error)

Connect request

func Delete

func Delete(rawurl string, ops ...OptionFunc) (*Response, error)

Delete request

func Do

func Do(req *http.Request) (*Response, error)

Do send http.Request

func Get

func Get(rawurl string, ops ...OptionFunc) (*Response, error)

Get request

func Head(rawurl string, ops ...OptionFunc) (*Response, error)

Head request

func Options

func Options(rawurl string, ops ...OptionFunc) (*Response, error)

Options request

func Patch

func Patch(rawurl string, ops ...OptionFunc) (*Response, error)

Patch request

func Post

func Post(rawurl string, ops ...OptionFunc) (*Response, error)

Post request

func PostFormData

func PostFormData(rawurl string, ops ...OptionFunc) (*Response, error)

PostFormData request

func Put

func Put(rawurl string, ops ...OptionFunc) (*Response, error)

Put request

func Suck

func Suck(req *Request, ops ...OptionFunc) (*Response, error)

Suck request suck data

func (*Response) GetBody

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

func (*Response) GetContextType

func (r *Response) GetContextType() string

func (*Response) GetHeader

func (r *Response) GetHeader() http.Header

func (*Response) GetHeaderSingle

func (r *Response) GetHeaderSingle(key string) string

func (*Response) GetHtml

func (r *Response) GetHtml() string

func (*Response) GetJson

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

func (*Response) GetXml

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

func (*Response) Read

func (r *Response) Read(p []byte) (n int, err error)

func (*Response) String

func (r *Response) String() string

func (*Response) TraceInfo added in v0.4.0

func (r *Response) TraceInfo() TraceInfo

TraceInfo method returns the trace info for the request. If either the Client or Request EnableTrace function has not been called prior to the request being made, an empty TraceInfo object will be returned.

Since v0.4.0

type Session

type Session struct {
	BaseURL string
	Header  http.Header
	Proxy   *url.URL
	Timeout time.Duration
	// contains filtered or unexported fields
}

Session is a http.Client

func DisableTrace added in v0.4.0

func DisableTrace() *Session

DisableTrace method disables the Quick client trace. Refer to `quick.EnableTrace`.

Since v0.4.0

func EnableTrace added in v0.4.0

func EnableTrace() *Session

EnableTrace method enables the Quick client trace for the requests fired from the client using `httptrace.ClientTrace` and provides insights.

resp, err := quick.EnableTrace().Get("https://httpbin.org/get")
fmt.Println("Error:", err)
fmt.Println("Trace Info:", resp.TraceInfo())

Also `Request.EnableTrace` available too to get trace info for single request.

Since v0.4.0

func InsecureSkipVerify

func InsecureSkipVerify(skip bool) *Session

InsecureSkipVerify ssl skip verify

func NewSession

func NewSession(options ...*SessionOptions) *Session

NewSession create a session

func SetBaseURL added in v0.4.0

func SetBaseURL(url string) *Session

SetBaseURL method is to set Base URL in the client instance. It will be used with request raised from this client with relative URL

// Setting HTTP address
quick.SetBaseURL("http://myjeeva.com")

// Setting HTTPS address
quick.SetBaseURL("https://myjeeva.com")

Since v0.4.0

func SetCheckRedirectHandler

func SetCheckRedirectHandler(handler func(req *http.Request, via []*http.Request) error) *Session

SetCheckRedirectHandler set global checkRedirect handler handler: func(req *http.Request, via []*http.Request) error

func SetCookieJar

func SetCookieJar(jar http.CookieJar) *Session

SetCookieJar set global cookieJar

func SetHeader

func SetHeader(h http.Header) *Session

SetHeader set global header

func SetHeaderSingle

func SetHeaderSingle(key, val string) *Session

SetHeaderSingle set global header single

func SetLogger added in v0.4.0

func SetLogger(l Logger) *Session

SetLogger method sets given writer for logging Quick request and response details.

Compliant to interface `quick.Logger`.

func SetProxyHandler

func SetProxyHandler(handler func(req *http.Request) (*url.URL, error)) *Session

SetProxyHandler set global proxy handler handler: func(req *http.Request) (*url.URL, error)

func SetProxyURL

func SetProxyURL(u *url.URL) *Session

SetProxyURL set global proxy url

func SetProxyUrl

func SetProxyUrl(rawurl string) *Session

SetProxyUrl set global proxy url

func SetTimeout

func SetTimeout(t time.Duration) *Session

SetTimeout set global request timeout example: time.Second * 30

func SetUserAgent

func SetUserAgent(ua string) *Session

SetUserAgent set global user-agent

func Use

func Use(middleware ...HandlerFunc) *Session

Use use middleware handler

func (*Session) Connect

func (session *Session) Connect(rawurl string, ops ...OptionFunc) (*Response, error)

Connect request

func (*Session) Cookies

func (session *Session) Cookies(rawurl string) Cookies

Cookies returns the cookies of the given url in Session.

func (*Session) Delete

func (session *Session) Delete(rawurl string, ops ...OptionFunc) (*Response, error)

Delete request

func (*Session) DisableTrace added in v0.4.0

func (session *Session) DisableTrace() *Session

DisableTrace method disables the Quick client trace. Refer to `Session.EnableTrace`.

Since v0.4.0

func (*Session) Do

func (session *Session) Do(req *http.Request) (*Response, error)

Do send http.Request

func (*Session) Download

func (session *Session) Download(rawurl string, toFile string) error

Download file

func (*Session) EnableTrace added in v0.4.0

func (session *Session) EnableTrace() *Session

EnableTrace method enables the Quick client trace for the requests fired from the client using `httptrace.ClientTrace` and provides insights.

session := quick.NewSession().EnableTrace()

resp, err := session.Get("https://httpbin.org/get")
fmt.Println("Error:", err)
fmt.Println("Trace Info:", resp.TraceInfo())

Also `Request.EnableTrace` available too to get trace info for single request.

Since v0.4.0

func (*Session) Get

func (session *Session) Get(rawurl string, ops ...OptionFunc) (*Response, error)

Get request

func (*Session) GetHeader

func (session *Session) GetHeader() http.Header

GetHeader get global header

func (*Session) GetHeaderSingle

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

GetHeaderSingle get session global header single

func (*Session) GetProxyURL

func (session *Session) GetProxyURL() *url.URL

GetProxyURL get session global proxy url

func (*Session) GetProxyUrl

func (session *Session) GetProxyUrl() string

GetProxyUrl get session global proxy url

func (*Session) GetUserAgent

func (session *Session) GetUserAgent() string

GetUserAgent get session global user-agent

func (*Session) Head

func (session *Session) Head(rawurl string, ops ...OptionFunc) (*Response, error)

Head request

func (*Session) InsecureSkipVerify

func (session *Session) InsecureSkipVerify(skip bool) *Session

InsecureSkipVerify ssl skip verify

func (*Session) Options

func (session *Session) Options(rawurl string, ops ...OptionFunc) (*Response, error)

Options request

func (*Session) Patch

func (session *Session) Patch(rawurl string, ops ...OptionFunc) (*Response, error)

Patch request

func (*Session) Post

func (session *Session) Post(rawurl string, ops ...OptionFunc) (*Response, error)

Post request

func (*Session) PostFormData

func (session *Session) PostFormData(rawurl string, ops ...OptionFunc) (*Response, error)

PostFormData postForm request

func (*Session) Put

func (session *Session) Put(rawurl string, ops ...OptionFunc) (*Response, error)

Put request

func (*Session) SetBaseURL added in v0.4.0

func (session *Session) SetBaseURL(url string) *Session

SetBaseURL method is to set Base URL in the client instance. It will be used with request raised from this client with relative URL

// Setting HTTP address
session.SetBaseURL("http://myjeeva.com")

// Setting HTTPS address
session.SetBaseURL("https://myjeeva.com")

Since v0.4.0

func (*Session) SetCheckRedirectHandler

func (session *Session) SetCheckRedirectHandler(handler func(req *http.Request, via []*http.Request) error) *Session

SetCheckRedirectHandler set session global checkRedirect handler. handler: func(req *http.Request, via []*http.Request) error

func (*Session) SetCookieJar

func (session *Session) SetCookieJar(jar http.CookieJar) *Session

SetCookieJar set session global cookieJar.

func (*Session) SetCookies

func (session *Session) SetCookies(rawurl string, cookies Cookies)

SetCookies set cookies of the url in Session.

func (*Session) SetHeader

func (session *Session) SetHeader(h http.Header) *Session

SetHeader set global header

func (*Session) SetHeaderSingle

func (session *Session) SetHeaderSingle(key, val string) *Session

SetHeaderSingle set session global header single

func (*Session) SetLogger added in v0.4.0

func (session *Session) SetLogger(l Logger) *Session

SetLogger method sets given writer for logging Quick request and response details.

Compliant to interface `quick.Logger`.

func (*Session) SetProxyHandler

func (session *Session) SetProxyHandler(handler func(req *http.Request) (*url.URL, error)) *Session

SetProxyHandler set session global proxy handler. handler: func(req *http.Request) (*url.URL, error)

func (*Session) SetProxyURL

func (session *Session) SetProxyURL(u *url.URL) *Session

SetProxyURL set session global proxy url

func (*Session) SetProxyUrl

func (session *Session) SetProxyUrl(rawurl string) *Session

SetProxyUrl set session global proxy url

func (*Session) SetTimeout

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

SetTimeout set session global request timeout example: time.Second * 30

func (*Session) SetUserAgent

func (session *Session) SetUserAgent(ua string) *Session

SetUserAgent set session global user-agent

func (*Session) Suck

func (session *Session) Suck(req *Request, ops ...OptionFunc) (*Response, error)

Suck request suck data

func (*Session) Use

func (session *Session) Use(middleware ...HandlerFunc) *Session

Use use middleware handler.

type SessionOptions

type SessionOptions struct {
	// DialTimeout is the maximum amount of time a dial will wait for
	// a connect to complete.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	DialTimeout time.Duration

	// DialKeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	//
	// Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	DialKeepAlive time.Duration

	// 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

	// 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

	// 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

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout 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 encode 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

	// DisableCookieJar specifies whether disable session cookiejar.
	DisableCookieJar bool

	// DisableDialKeepAlives, 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.
	DisableDialKeepAlives bool
}

func DefaultSessionOptions

func DefaultSessionOptions() *SessionOptions

DefaultSessionOptions return a default SessionOptions object.

type TraceInfo added in v0.4.0

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 Quick
	// 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 v0.4.0

func (TraceInfo) String added in v0.4.0

func (t TraceInfo) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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