v1.9.1 Latest Latest

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

Go to latest
Published: Oct 21, 2021 License: BSD-2-Clause Imports: 20 Imported by: 0




View Source
const (
	HeaderAccept                        string = "Accept"
	HeaderAcceptCharset                 string = "Accept-Charset"
	HeaderAcceptFeatures                string = "Accept-Features"
	HeaderAcceptEncoding                string = "Accept-Encoding"
	HeaderAcceptLanguage                string = "Accept-Language"
	HeaderAcceptRanges                  string = "Accept-Ranges"
	HeaderAccessControlAllowCredentials string = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowOrigin      string = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     string = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     string = "Access-Control-Allow-Headers"
	HeaderAccessControlMaxAge           string = "Access-Control-Max-Age"
	HeaderAccessControlExposeHeaders    string = "Access-Control-Expose-Headers"
	HeaderAccessControlRequestMethod    string = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   string = "Access-Control-Request-Headers"
	HeaderAge                           string = "Age"
	HeaderAllow                         string = "Allow"
	HeaderAlternates                    string = "Alternates"
	HeaderAuthorization                 string = "Authorization"
	HeaderCacheControl                  string = "Cache-Control"
	HeaderConnection                    string = "Connection"
	HeaderContentEncoding               string = "Content-Encoding"
	HeaderContentLanguage               string = "Content-Language"
	HeaderContentLength                 string = "Content-Length"
	HeaderContentLocation               string = "Content-Location"
	HeaderContentMD5                    string = "Content-MD5"
	HeaderContentRange                  string = "Content-Range"
	HeaderContentSecurityPolicy         string = "Content-Security-Policy"
	HeaderContenttype                   string = "Content-Type"
	HeaderCookie                        string = "Cookie"
	HeaderDNT                           string = "DNT"
	HeaderDate                          string = "Date"
	HeaderETag                          string = "ETag"
	HeaderExpect                        string = "Expect"
	HeaderExpires                       string = "Expires"
	HeaderFrom                          string = "From"
	HeaderHost                          string = "Host"
	HeaderIfMatch                       string = "If-Match"
	HeaderIfModifiedSince               string = "If-Modified-Since"
	HeaderIfNoneMatch                   string = "If-None-Match"
	HeaderIfRange                       string = "If-Range"
	HeaderIfUnmodifiedSince             string = "If-Unmodified-Since"
	HeaderLastEventID                   string = "Last-Event-ID"
	HeaderLastModified                  string = "Last-Modified"
	HeaderLink                          string = "Link"
	HeaderLocation                      string = "Location"
	HeaderMaxForwards                   string = "Max-Forwards"
	HeaderNegotiate                     string = "Negotiate"
	HeaderOrigin                        string = "Origin"
	HeaderPragma                        string = "Pragma"
	HeaderProxyAuthenticate             string = "Proxy-Authenticate"
	HeaderProxyAuthorization            string = "Proxy-Authorization"
	HeaderRange                         string = "Range"
	HeaderReferer                       string = "Referer"
	HeaderRetryAfter                    string = "Retry-After"
	HeaderSecWebsocketExtensions        string = "Sec-Websocket-Extensions"
	HeaderSecWebsocketKey               string = "Sec-Websocket-Key"
	HeaderSecWebsocketOrigin            string = "Sec-Websocket-Origin"
	HeaderSecWebsocketProtocol          string = "Sec-Websocket-Protocol"
	HeaderSecWebsocketVersion           string = "Sec-Websocket-Version"
	HeaderServer                        string = "Server"
	HeaderSetCookie                     string = "Set-Cookie"
	HeaderSetCookie2                    string = "Set-Cookie2"
	HeaderStrictTransportSecurity       string = "Strict-Transport-Security"
	HeaderTransferEncoding              string = "Transfer-Encoding"
	HeaderUpgrade                       string = "Upgrade"
	HeaderUserAgent                     string = "User-Agent"
	HeaderVariantVary                   string = "Variant-Vary"
	HeaderVary                          string = "Vary"
	HeaderVia                           string = "Via"
	HeaderWarning                       string = "Warning"
	HeaderWWWAuthenticate               string = "WWW-Authenticate"
	HeaderXContentDuration              string = "X-Content-Duration"
	HeaderXContentSecurityPolicy        string = "X-Content-Security-Policy"
	HeaderXDNSPrefetchControl           string = "X-DNSPrefetch-Control"
	HeaderXFrameOptions                 string = "X-Frame-Options"
	HeaderXRequestedWith                string = "X-Requested-With"

header names

View Source
const (
	MimetypeJson        = "application/json"
	MimetypeFormEncoded = "application/x-www-form-urlencoded"
	MimeTypeOctetStream = "application/octet-stream"

	MimeTypePlainText  = "text/plain"
	MimeTypeCSS        = "text/css"
	MimeTypeHTML       = "text/html"
	MimeTypeJavascript = "text/javascript"

	MimeTypeMultipart = "multipart/form-data"

	MimeTypeAPNG = "image/apng"
	MimeTypeBMP  = "image/bmp"
	MimeTypeGIF  = "image/gif"
	MimeTypeICO  = "image/x-icon"
	MimeTypeJPG  = "image/jpeg"
	MimeTypePNG  = "image/png"
	MimeTypeSVG  = "image/svg+xml"
	MimeTypeTIFF = "image/tiff"
	MimeTypeWEBP = "image/webp"

mime types


This section is empty.


func DecodeQuery

func DecodeQuery(str string, enc encoding.Encoding) (string, error)

DecodeQuery decode a single str token to http param key or value.

func EncodeParams

func EncodeParams(enc encoding.Encoding, params ...*Param) (string, error)

EncodeParams encode params to encoded str.

func EncodeParamsTo

func EncodeParamsTo(buf strings.Builder, enc encoding.Encoding, params ...*Param) error

EncodeParamsTo encode params, and write to buf.

func EncodeQuery

func EncodeQuery(str string, enc encoding.Encoding) (string, error)

EncodeQuery encode a single str token as http param key or value.

func FormatDateHeader

func FormatDateHeader(date time.Time) string

FormatDateHeader convert date to http header value.

func ParseDateHeader

func ParseDateHeader(dateStr string) (time.Time, error)

ParseDateHeader parse date header value, and return time in current Location.


type Body

type Body interface {
	// MimeType return content mime type of this body
	MimeType() string

	// Encoding for body. may be nil
	Encoding() encoding.Encoding

	// GetReader get a reader for reading body data
	GetReader() (io.Reader, error)

Body is interface for Http body, with content type

func EmptyBody

func EmptyBody() Body

EmptyBody return an empty http Body

type BytesBody

type BytesBody struct {
	// contains filtered or unexported fields

BytesBody is a http body contains byte array as content

func NewBytesBody

func NewBytesBody(data []byte, contentType string) *BytesBody

NewBytesBody create new Body from bytes, providing mimetype

func NewBytesBodyWithEncoding

func NewBytesBodyWithEncoding(data []byte, contentType string, enc encoding.Encoding) *BytesBody

NewBytesBodyWithEncoding create new Body from bytes, and provide mimetype, and encoding

func (*BytesBody) Encoding

func (b *BytesBody) Encoding() encoding.Encoding

func (*BytesBody) GetReader

func (b *BytesBody) GetReader() (io.Reader, error)

func (*BytesBody) MimeType

func (h *BytesBody) MimeType() string

type Client

type Client struct {
	// contains filtered or unexported fields

Client means Http Client

func NewClient

func NewClient(options ...ClientOption) *Client

NewClient create new http client

func (*Client) Delete

func (c *Client) Delete(url string, options ...RequestOption) *ResponseHolder

Delete send a delete request

func (*Client) Get

func (c *Client) Get(url string, options ...RequestOption) *ResponseHolder

Get send a get request

func (*Client) Head

func (c *Client) Head(url string, options ...RequestOption) *ResponseHolder

Head send a head request

func (*Client) Post

func (c *Client) Post(url string, body Body, options ...RequestOption) *ResponseHolder

Post send a post request with body

func (*Client) Put

func (c *Client) Put(url string, body Body, options ...RequestOption) *ResponseHolder

Put put send a put request with body

func (*Client) Send

func (c *Client) Send(r *http.Request, options ...RequestOption) *ResponseHolder

Send send a http request with options.

type ClientOption

type ClientOption func(client *Client)

ClientOption for setting http client option.

func DialTimeout

func DialTimeout(timeout time.Duration) ClientOption

DialTimeout set tcp dial timeout

func DisableCompression

func DisableCompression() ClientOption

DisableCompression prevents the client from requesting compression with an "Accept-Encoding: gzip"

func DisableFollowRedirects

func DisableFollowRedirects() ClientOption

DisableFollowRedirects disable redirect handle

func DisableHTTPKeepAlive

func DisableHTTPKeepAlive() ClientOption

DisableHTTPKeepAlive disable Http keep alive(which means disable http connection reuse)

func DisableTCPKeepAlive

func DisableTCPKeepAlive() ClientOption

DisableTCPKeepAlive disable tcp connection keep alive

func DisableTLSVerify

func DisableTLSVerify() ClientOption

DisableTLSVerify disable tls certificate chain and server name verifying.

func EnableCookie

func EnableCookie() ClientOption

EnableCookie enable auto cookie handle (receive, store, send)

func ExpectContinueTimeout

func ExpectContinueTimeout(timeout time.Duration) ClientOption

ExpectContinueTimeout set max duration for waiting a server's first response headers after fully writing the request headers if the request has an "Expect: 100-continue" header. Default is not timeout

func IdleConnTimeout

func IdleConnTimeout(timeout time.Duration) ClientOption

IdleConnTimeout set max duration for close idle connections. Default is not timeout

func MaxConnsPerHost

func MaxConnsPerHost(count int) ClientOption

MaxConnsPerHost set max connection count for one host. Default is no limit

func MaxIdleConns

func MaxIdleConns(count int) ClientOption

MaxIdleConns set max count for all hosts of this client. Default is no limit

func MaxIdleConnsPerHost

func MaxIdleConnsPerHost(count int) ClientOption

MaxIdleConnsPerHost set max idle connection count for one host. Default is no limit

func RequestTimeout

func RequestTimeout(timeout time.Duration) ClientOption

RequestTimeout set http client timeout for one request

func ResponseHeaderTimeout

func ResponseHeaderTimeout(timeout time.Duration) ClientOption

ResponseHeaderTimeout set max duration for wait response header after write all request. Default is no timeout.

func UseProxy

func UseProxy(proxy string) ClientOption

UseProxy set proxy by proxy url. 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 url parse error, no proxy is used.

func UserAgent

func UserAgent(userAgent string) ClientOption

UserAgent set use-agent for this client

type Cookie = http.Cookie

Cookie is an alias for http.Cookie

type FormBody

type FormBody struct {
	// contains filtered or unexported fields

FormBody is url-encoded-www form body

func NewFormBody

func NewFormBody(params ...*Param) *FormBody

NewFormBody create new form encoded Body from params

func NewFormBodyWithEncoding

func NewFormBodyWithEncoding(params []*Param, enc encoding.Encoding) *FormBody

NewFormBodyWithEncoding create new form encoded Body from params

func (*FormBody) Encoding

func (e *FormBody) Encoding() encoding.Encoding

func (*FormBody) GetReader

func (f *FormBody) GetReader() (io.Reader, error)

func (*FormBody) MimeType

func (f *FormBody) MimeType() string
type Header struct {
	Name  string
	Value string

Header is one http header. including name and value.

func NewDateHeader

func NewDateHeader(name string, value time.Time) *Header

NewDateHeader create one new header, with date time value.

func NewHeader

func NewHeader(name, value string) *Header

NewHeader create one new header

func (*Header) Unpack

func (h *Header) Unpack() (name, value string)

Unpack return contents for convenient assign to multi variables.

type JSONBody

type JSONBody struct {
	// contains filtered or unexported fields

JSONBody is http body, marshal value as json

func NewJSONBody

func NewJSONBody(value interface{}) *JSONBody

NewJSONBody create new Body from value, marshall to json

func NewJSONBodyWithEncoding

func NewJSONBodyWithEncoding(value interface{}, enc encoding.Encoding) *JSONBody

NewJSONBodyWithEncoding create new Body from value, marshall to json

func (*JSONBody) Encoding

func (e *JSONBody) Encoding() encoding.Encoding

func (*JSONBody) GetReader

func (j *JSONBody) GetReader() (io.Reader, error)

func (*JSONBody) MimeType

func (j *JSONBody) MimeType() string

type MimeType

type MimeType struct {
	Type    string // the type
	SubType string // the subtype

MimeType is for http mime type.

func ParseMimeType

func ParseMimeType(mimeType string) *MimeType

ParseMimeType parse a mimetype string to type and subtype. This function always return with no error, but results may be undefined and vary for invalid input mime-type strings.

func (*MimeType) String

func (m *MimeType) String() string

func (*MimeType) Unpack

func (m *MimeType) Unpack() (_type, subType string)

Unpack is for convenient unpack mime type values.

type MultiPartBody

type MultiPartBody struct {
	// contains filtered or unexported fields

MultiPartBody is http multi-part form body

func NewMultiPartBody

func NewMultiPartBody(parts []*Part) *MultiPartBody

NewMultiPartBody create new multi part body

func (*MultiPartBody) Encoding

func (m *MultiPartBody) Encoding() encoding.Encoding

func (*MultiPartBody) GetReader

func (m *MultiPartBody) GetReader() (io.Reader, error)

func (*MultiPartBody) MimeType

func (m *MultiPartBody) MimeType() string

type Param

type Param struct {
	Name  string
	Value string

Param is a http get param key/value, or www-form-encoded post param.

func NewParam

func NewParam(name string, value string) *Param

NewParam create new param

func ParseParam

func ParseParam(str string) *Param

ParseParam parse xx=xx to param. The white space char with '=' will be trimmed. If str do not contains '=', the str is treat as key. If contains multi '=', use the first one.

type Part

type Part struct {
	// contains filtered or unexported fields

Part is one part of multi-part encoded body, can be key-value form field, or form file part.

func NewBytesFilePart

func NewBytesFilePart(name string, filename string, data []byte) *Part

NewBytesFilePart create one new file Part from binary array.

func NewFSFilePart

func NewFSFilePart(name string, filename string, path string) *Part

NewFSFilePart create one new file Part from a file in file system.

func NewFilePart

func NewFilePart(name string, filename string, readerProvider func() (io.Reader, error)) *Part

NewFilePart create one new file Part. param readerProvider provide the reader contains the content of this part, should allow call multi times.

func NewFormPart

func NewFormPart(name string, value string) *Part

NewFormPart create one new key-value param Part.

type ReaderBody

type ReaderBody struct {
	// contains filtered or unexported fields

ReaderBody is a http body contains a io.Reader

func NewBody

func NewBody(reader io.Reader, contentType string) *ReaderBody

NewBody create new Body from reader

func NewBodyWithEncoding

func NewBodyWithEncoding(reader io.Reader, contentType string, enc encoding.Encoding) *ReaderBody

NewBodyWithEncoding create new Body from reader

func (*ReaderBody) Encoding

func (e *ReaderBody) Encoding() encoding.Encoding

func (*ReaderBody) GetReader

func (r *ReaderBody) GetReader() (io.Reader, error)

func (*ReaderBody) MimeType

func (h *ReaderBody) MimeType() string

type RequestOption

type RequestOption func(r *http.Request) (error, *http.Request)

RequestOption is defined for custom Http Request

func AddCookie

func AddCookie(name, value string) RequestOption

AddCookie add a cookie to request

func AddCookies

func AddCookies(cookies map[string]string) RequestOption

AddCookies add cookies to request

func AddCookies2

func AddCookies2(firstCookie *Cookie, cookies ...*Cookie) RequestOption

AddCookies2 add cookies to request

func AddHeader

func AddHeader(name, value string) RequestOption

AddHeader add a header to request.For host header, use SetHost.

func AddHeaders

func AddHeaders(headers map[string]string) RequestOption

AddHeaders add headers to request.For host header, use SetHost.

func AddHeaders2

func AddHeaders2(headers ...*Header) RequestOption

AddHeaders2 add headers to request.For host header, use SetHost.

func BasicAuth

func BasicAuth(user, password string) RequestOption

BasicAuth set request HTTP Basic Authentication with the provided username and password

func SetHeader

func SetHeader(name, value string) RequestOption

SetHeader set a header. For host header, use SetHost.

func SetHeaders

func SetHeaders(headers map[string]string) RequestOption

SetHeaders set headers. For host header, use SetHost.

func SetHeaders2

func SetHeaders2(headers ...*Header) RequestOption

SetHeaders2 set headers. For host header, use SetHost.

func SetHost

func SetHost(host string) RequestOption

SetHost set Host header for request. The host header cannot set by SetHeader

func SetQueries

func SetQueries(params ...*Param) RequestOption

SetQueries add query params to url. The params key/value will be encoded.

func SetQueriesWithEncoding

func SetQueriesWithEncoding(enc encoding.Encoding, params ...*Param) RequestOption

SetQueriesWithEncoding add query params to url. The params key/value will be encoded using specified encoding.

func WithContext

func WithContext(ctx context.Context) RequestOption

WithContext set the context for request

type ResponseHeader

type ResponseHeader struct {
	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 maps header keys to values. If the response had multiple
	// headers with the same key, they may be concatenated, with comma
	// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) When
	// Header values are duplicated by other fields in this struct (e.g.,
	// ContentLength, TransferEncoding, Trailer), the field values are
	// authoritative.
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	Header http.Header

	// Trailer maps trailer keys to values in the same
	// format as Header.
	// The Trailer initially contains only nil values, one for
	// each key specified in the server's "Trailer" header
	// value. Those values are not added to Header.
	// Trailer must not be accessed concurrently with Read calls
	// on the Body.
	// After Body.Read has returned io.EOF, Trailer will contain
	// any trailer values sent by the server.
	Trailer http.Header

ResponseHeader is a http response without body...

type ResponseHolder

type ResponseHolder struct {
	Response *http.Response
	Err      error

ResponseHolder carry http response and errors.

func (*ResponseHolder) DecodeJSON

func (r *ResponseHolder) DecodeJSON(v interface{}) (*ResponseHeader, error)

DecodeJSON decode http body as json, into a value.

func (*ResponseHolder) DiscardBody

func (r *ResponseHolder) DiscardBody() (*ResponseHeader, error)

DiscardBody read and discard all response body

func (*ResponseHolder) GetEncoding

func (r *ResponseHolder) GetEncoding() encoding.Encoding

GetEncoding get encoding from response header. If header not set charset for content-type, return nil.

func (*ResponseHolder) ReadAll

func (r *ResponseHolder) ReadAll() (*ResponseHeader, []byte, error)

ReadAll read all response body, to bytes

func (*ResponseHolder) ReadAllString

func (r *ResponseHolder) ReadAllString() (*ResponseHeader, string, error)

ReadAllString read all response body, to string

func (*ResponseHolder) WriteToFile

func (r *ResponseHolder) WriteToFile(path string) (*ResponseHeader, error)

WriteToFile read all response body, write to file.

func (*ResponseHolder) WriteToWriter

func (r *ResponseHolder) WriteToWriter(w io.Writer) (*ResponseHeader, error)

WriteToWriter read all response body data, and write to target writer.

type StringBody

type StringBody struct {
	// contains filtered or unexported fields

StringBody is a http body has string value

func NewStringBody

func NewStringBody(content string, contentType string) *StringBody

NewStringBody create new Body from string content

func NewStringBodyWithEncoding

func NewStringBodyWithEncoding(content string, contentType string, enc encoding.Encoding) *StringBody

NewStringBodyWithEncoding create new Body from string

func (*StringBody) Encoding

func (e *StringBody) Encoding() encoding.Encoding

func (*StringBody) GetReader

func (s *StringBody) GetReader() (io.Reader, error)

func (*StringBody) MimeType

func (h *StringBody) MimeType() string

Jump to

Keyboard shortcuts

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