Documentation ¶
Overview ¶
Utilities for extracting and formatting data encountered in HTTP requests
Index ¶
- Constants
- Variables
- func AddQ(u *url.URL, key string, values ...interface{})
- func AddQString(u string, key string, value interface{}) string
- func DecodeResponse(response *http.Response) (io.Reader, error)
- func DelQ(u *url.URL, key string)
- func DelQString(u string, key string) string
- func EncodeBasicAuth(username string, password string) string
- func Is1xx(code int) bool
- func Is2xx(code int) bool
- func Is3xx(code int) bool
- func Is4xx(code int) bool
- func Is5xx(code int) bool
- func IsHttpErr(err error) bool
- func IsMediaType(req *http.Request, mediaTypes ...string) bool
- func JSONDecoder(in io.Reader, out interface{}) error
- func JSONEncoder(in interface{}) (io.Reader, error)
- func LoadCertPool(filename string) (*x509.CertPool, error)
- func MediaType(req *http.Request) string
- func MultipartFormEncoder(in interface{}) (io.Reader, error)
- func ParseFormRequest(req *http.Request, into interface{}) error
- func ParseFormValues(formValues url.Values, into interface{}) error
- func ParseJSON(r io.Reader, into interface{}) error
- func ParseJSONRequest(req *http.Request, into interface{}) error
- func ParseRequest(req *http.Request, into interface{}) error
- func Q(req *http.Request, key string, fallbacks ...string) string
- func QBool(req *http.Request, key string, fallbacks ...bool) bool
- func QDuration(req *http.Request, key string) time.Duration
- func QFloat(req *http.Request, key string, fallbacks ...float64) float64
- func QInt(req *http.Request, key string, fallbacks ...int64) int64
- func QStrings(req *http.Request, key string, delimiter string, fallbacks ...string) []string
- func QTime(req *http.Request, key string) time.Time
- func RequestGetValue(req *http.Request, key string) typeutil.Variant
- func RequestSetValue(req *http.Request, key string, value interface{})
- func RespondJSON(w http.ResponseWriter, data interface{}, status ...int)
- func SetContentTypeParser(contentType string, parser RequestParseFunc)
- func SetQ(u *url.URL, key string, value interface{})
- func SetQString(u string, key string, value interface{}) string
- func SetRootCABundle(client *http.Client, caBundle string) error
- func UrlPathJoin(baseurl interface{}, path string) (*url.URL, error)
- func WaitForHTTP(url string, timeout time.Duration, c ...*http.Client) error
- type Client
- func (self *Client) AppendTrustedRootCA(pemFilenamesOrData ...interface{}) error
- func (self *Client) ClearHeaders()
- func (self *Client) ClearParams()
- func (self *Client) Client() *http.Client
- func (self *Client) Decode(r io.Reader, out interface{}) error
- func (self *Client) Delete(path string, params map[string]interface{}, headers map[string]interface{}) (*http.Response, error)
- func (self *Client) Encode(in interface{}) ([]byte, error)
- func (self *Client) Get(path string, params map[string]interface{}, headers map[string]interface{}) (*http.Response, error)
- func (self *Client) GetWithBody(path string, body interface{}, params map[string]interface{}, ...) (*http.Response, error)
- func (self *Client) Headers() http.Header
- func (self *Client) Params() map[string]interface{}
- func (self *Client) Post(path string, body interface{}, params map[string]interface{}, ...) (*http.Response, error)
- func (self *Client) Put(path string, body interface{}, params map[string]interface{}, ...) (*http.Response, error)
- func (self *Client) Request(method Method, path string, body interface{}, params map[string]interface{}, ...) (*http.Response, error)
- func (self *Client) SetBasicAuth(username string, password string)
- func (self *Client) SetClient(client *http.Client)
- func (self *Client) SetDecoder(fn DecoderFunc)
- func (self *Client) SetEncoder(fn EncoderFunc)
- func (self *Client) SetErrorDecoder(fn ErrorDecoderFunc)
- func (self *Client) SetHeader(name string, value interface{})
- func (self *Client) SetInsecureTLS(insecure bool)
- func (self *Client) SetParam(name string, value interface{})
- func (self *Client) SetPostRequestHook(fn InterceptResponseFunc)
- func (self *Client) SetPreRequestHook(fn InterceptRequestFunc)
- func (self *Client) SetRootCA(pemFilenamesOrData ...interface{}) error
- func (self *Client) URI() *url.URL
- func (self *Client) WithDecoder(fn DecoderFunc) *Client
- func (self *Client) WithEncoder(fn EncoderFunc) *Client
- type DecoderFunc
- type EncoderFunc
- type ErrorDecoderFunc
- type InterceptRequestFunc
- type InterceptResponseFunc
- type LogLevel
- type Method
- type MultipartFormFile
- type RequestLoggerdeprecated
- type RequestParseFunc
- type WritableLogger
Examples ¶
- IsMediaType (MediaTypePrefix)
- IsMediaType (MultipleMediaTypes)
- IsMediaType (NonMatchingPrefix)
- IsMediaType (SingleMediaType)
- UrlPathJoin (EmptyJoin)
- UrlPathJoin (JoinToExistingQueryStrings)
- UrlPathJoin (JoinWithQueryString)
- UrlPathJoin (PathAndQuery)
- UrlPathJoin (PathAndQueryTrailingSlash)
- UrlPathJoin (SimpleJoin)
- UrlPathJoin (SlashJoin)
Constants ¶
const ( Get Method = `GET` Post = `POST` Put = `PUT` Delete = `DELETE` Head = `HEAD` Options = `OPTIONS` Patch = `PATCH` )
Variables ¶
var DebugOutputBoxWidth = 60
var DefaultMultipartFormFileField = `filename`
var FormUnmarshalStructTag = `json`
var Logger = logging.MustGetLogger(`httputil`)
var WaitForPollInterval = time.Second
Functions ¶
func AddQString ¶ added in v1.8.6
A version of AddQ that accepts a URL string and makes a best-effort to modify it. Will return the modified URL or the original URL if an error occurred.
func DecodeResponse ¶
Takes an http.Response and returns an io.Reader that will return the contents of the Response Body decoded according to the values (if any) of the Content-Encoding response header.
func DelQString ¶ added in v1.8.6
A version of DelQ that accepts a URL string and makes a best-effort to modify it. Will return the modified URL or the original URL if an error occurred.
func EncodeBasicAuth ¶ added in v1.7.28
Encode the username and password into a value than can be used in the Authorization HTTP header.
func IsMediaType ¶ added in v1.8.43
Returns whether the Content-Type of the given request matches any of the supplied options. The mediaTypes arguments may be either complete media types (e.g.: "text/html", "application/javascript") or major type classes (e.g.: "text/", "video/"). The trailing slash (/) indicates that any media type that begins with that text will match.
Example (MediaTypePrefix) ¶
req := httptest.NewRequest(`GET`, `/`, nil) req.Header.Set(`Content-Type`, `text/html; charset=utf-8`) fmt.Println(IsMediaType(req, `text/`))
Output: true
Example (MultipleMediaTypes) ¶
req := httptest.NewRequest(`GET`, `/`, nil) req.Header.Set(`Content-Type`, `text/html; charset=utf-8`) fmt.Println(IsMediaType(req, `text/html`, `text/plain`))
Output: true
Example (NonMatchingPrefix) ¶
req := httptest.NewRequest(`GET`, `/`, nil) req.Header.Set(`Content-Type`, `text/html; charset=utf-8`) fmt.Println(IsMediaType(req, `video/`))
Output: false
Example (SingleMediaType) ¶
req := httptest.NewRequest(`GET`, `/`, nil) req.Header.Set(`Content-Type`, `text/html; charset=utf-8`) fmt.Println(IsMediaType(req, `text/html`))
Output: true
func JSONDecoder ¶
func JSONEncoder ¶
func LoadCertPool ¶ added in v1.6.25
Loads certificates from the given file and returns a usable x509.CertPool
func MultipartFormEncoder ¶ added in v1.7.40
Specifies that the given data should be encoded as a multipart/form-data request.
func ParseFormRequest ¶
Parses the form values for a Request and unmarshals into the given value.
func ParseFormValues ¶
Parses a set of values received from an HTML form (usually the value of the http.Request.Form property) and unmarshals into the given value.
func ParseJSONRequest ¶
Parses the Request as JSON and unmarshals into the given value.
func ParseRequest ¶
Autodetect the Content-Type of the given request and unmarshals into the given value.
func QDuration ¶ added in v1.6.23
Parses the named query string from a request as a duration string.
func QStrings ¶ added in v1.5.58
Parses the named query string from a request as a delimiter-separated string slice.
func RequestGetValue ¶ added in v1.8.28
Retrieve an arbitrary value from the context of a given request.
func RequestSetValue ¶ added in v1.8.28
attach an arbitrary value to the context of a given request.
func RespondJSON ¶
func RespondJSON(w http.ResponseWriter, data interface{}, status ...int)
Marshal the given data as a JSON document and write the output to the given ResponseWriter. If a status is given, that will be used as the HTTP response status. If data is an error, and no status is given, the status will be "500 Internal Server Error"; if data is nil, the status will be "204 No Content". The Content-Type of the response is "application/json".
func SetContentTypeParser ¶
func SetContentTypeParser(contentType string, parser RequestParseFunc)
Sets a parser implementation for the given HTTP content type.
func SetQString ¶ added in v1.8.6
A version of SetQ that accepts a URL string and makes a best-effort to modify it. Will return the modified URL or the original URL if an error occurred.
func SetRootCABundle ¶ added in v1.6.24
Configures the given http.Client to accept TLS certificates validated by the given PEM-encoded CA bundle file
func UrlPathJoin ¶ added in v1.8.53
UrlPathJoin takes a string or *url.URL and joins the existing URL path component with the given path. The new path may also contain query string values, which will be added to the base URL. Existing keys will be replaced with new ones, except for repeated keys (e.g.: ?x=1&x=2&x=3). In this case, the new values will be added to the existing ones. The *url.URL returned from this function is a copy, and the original URL (if one is provided) will not be modified in any way.
Example (EmptyJoin) ¶
url, _ := UrlPathJoin(`https://google.com/`, ``) fmt.Println(url.String())
Output: https://google.com/
Example (JoinToExistingQueryStrings) ¶
url, _ := UrlPathJoin(`https://google.com/search`, `?q=hello`) fmt.Println(url.String())
Output: https://google.com/search?q=hello
Example (JoinWithQueryString) ¶
url, _ := UrlPathJoin(`https://google.com/`, `/search?q=hello`) fmt.Println(url.String())
Output: https://google.com/search?q=hello
Example (PathAndQuery) ¶
url, _ := UrlPathJoin(`https://example.com/api/v1?hello=there`, `/things/new?example=true`) fmt.Println(url.String())
Output: https://example.com/api/v1/things/new?example=true&hello=there
Example (PathAndQueryTrailingSlash) ¶
url, _ := UrlPathJoin(`https://example.com/api/v1?hello=there`, `/things/new/?example=true`) fmt.Println(url.String())
Output: https://example.com/api/v1/things/new/?example=true&hello=there
Example (SimpleJoin) ¶
url, _ := UrlPathJoin(`https://google.com`, `/search`) fmt.Println(url.String())
Output: https://google.com/search
Example (SlashJoin) ¶
url, _ := UrlPathJoin(`https://google.com/`, `/`) fmt.Println(url.String())
Output: https://google.com/
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) AppendTrustedRootCA ¶ added in v1.7.25
Append one or more trusted certificates to the RootCA bundle that is consulted when performing HTTPS requests.
func (*Client) ClearHeaders ¶
func (self *Client) ClearHeaders()
Remove all implicit HTTP request headers.
func (*Client) ClearParams ¶
func (self *Client) ClearParams()
Remove all implicit querystring parameters.
func (*Client) GetWithBody ¶
func (*Client) Request ¶
func (self *Client) Request( method Method, path string, body interface{}, params map[string]interface{}, headers map[string]interface{}, ) (*http.Response, error)
Perform an HTTP request
func (*Client) SetBasicAuth ¶ added in v1.7.28
Set the username and password to be included in the Authorization header.
func (*Client) SetDecoder ¶
func (self *Client) SetDecoder(fn DecoderFunc)
Specify a decoder that will be used to deserialize data in the response body.
func (*Client) SetEncoder ¶
func (self *Client) SetEncoder(fn EncoderFunc)
Specify an encoder that will be used to serialize data in the request body.
func (*Client) SetErrorDecoder ¶
func (self *Client) SetErrorDecoder(fn ErrorDecoderFunc)
Specify a different decoder used to deserialize non 2xx/3xx HTTP responses.
func (*Client) SetHeader ¶
Add an HTTP request header by name that will be included in every request. If value is nil, the named header will be removed instead.
func (*Client) SetInsecureTLS ¶ added in v1.7.26
Set or unset insecure TLS requests that will proceed even if the peer certificate cannot be verified.
func (*Client) SetParam ¶
Add a querystring parameter by name that will be included in every request. If value is nil, the parameter will be removed instead.
func (*Client) SetPostRequestHook ¶
func (self *Client) SetPostRequestHook(fn InterceptResponseFunc)
Specify a function tht will be called immediately after a response is received. This function is given the first opportunity to inspect the response, and if it returns a non-nil error, no additional processing (including the Error Decoder function) will be performed.
func (*Client) SetPreRequestHook ¶
func (self *Client) SetPreRequestHook(fn InterceptRequestFunc)
Specify a function that will be called immediately before a request is sent. This function has an opportunity to read and modify the outgoing request, and if it returns a non-nil error, the request will not be sent.
func (*Client) SetRootCA ¶ added in v1.7.25
Replace the existing RootCA bundle with an explicit set of trusted certificates.
func (*Client) WithDecoder ¶ added in v1.7.40
func (self *Client) WithDecoder(fn DecoderFunc) *Client
Return a copy of the current client that uses a different decoder.
func (*Client) WithEncoder ¶ added in v1.7.40
func (self *Client) WithEncoder(fn EncoderFunc) *Client
Return a copy of the current client that uses a different encoder.
type DecoderFunc ¶
type EncoderFunc ¶
type ErrorDecoderFunc ¶
type InterceptRequestFunc ¶
type InterceptResponseFunc ¶
type MultipartFormFile ¶ added in v1.7.40
type RequestLogger
deprecated
type RequestLogger struct { }
Deprecated: this type will go away in 1.9.x
func NewRequestLogger ¶
func NewRequestLogger() *RequestLogger
func (*RequestLogger) ServeHTTP ¶
func (self *RequestLogger) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc)
type RequestParseFunc ¶
type WritableLogger ¶
type WritableLogger struct {
// contains filtered or unexported fields
}
func NewWritableLogger ¶
func NewWritableLogger(level LogLevel, prefix ...string) *WritableLogger