Documentation ¶
Index ¶
- Constants
- func ForkReadCloser(val io.ReadCloser) (_, _ io.ReadCloser)
- func IsClientErr(val int) bool
- func IsInfo(val int) bool
- func IsNil(val interface{}) bool
- func IsOk(val int) bool
- func IsReadOnly(val string) bool
- func IsRedir(val int) bool
- func IsServerErr(val int) bool
- func Str(src interface{}) string
- func UrlAppend(ref *url.URL, val interface{}) *url.URL
- func UrlJoin(ref *url.URL, vals ...interface{}) *url.URL
- type BytesReadCloser
- type Cli
- type Err
- type Head
- func (self Head) Add(key, val string) Head
- func (self Head) Clone() Head
- func (self Head) Del(key string) Head
- func (self Head) Get(key string) string
- func (self Head) Has(key string) bool
- func (self Head) Header() http.Header
- func (self Head) Init() Head
- func (self Head) Patch(head map[string][]string) Head
- func (self Head) Replace(key string, vals ...string) Head
- func (self Head) Set(key, val string) Head
- func (self Head) Values(key string) []string
- type Req
- func Connect() *Req
- func Ctx(ctx context.Context) *Req
- func Delete() *Req
- func Get() *Req
- func Init() *Req
- func Meth(val string) *Req
- func Options() *Req
- func Patch() *Req
- func Path(val string, vals ...interface{}) *Req
- func Post() *Req
- func Put() *Req
- func To(val string) *Req
- func Trace() *Req
- func Url(val *url.URL) *Req
- func (self *Req) Append(val interface{}) *Req
- func (self *Req) Bytes(val []byte) *Req
- func (self *Req) Cli(val *http.Client) *Req
- func (self *Req) CliRes(cli *http.Client) *Res
- func (self *Req) CliResCatch(cli *http.Client) (_ *Res, err error)
- func (self *Req) Client() *http.Client
- func (self *Req) Clone() *Req
- func (self *Req) CloneBody() io.ReadCloser
- func (self *Req) Connect() *Req
- func (self *Req) Context() context.Context
- func (self *Req) Ctx(ctx context.Context) *Req
- func (self *Req) Delete() *Req
- func (self *Req) Dump() *Req
- func (self *Req) FormVals(val map[string][]string) *Req
- func (self *Req) Get() *Req
- func (self *Req) Head(val map[string][]string) *Req
- func (self *Req) HeadAdd(key, val string) *Req
- func (self *Req) HeadDel(key string) *Req
- func (self *Req) HeadInit() *Req
- func (self *Req) HeadPatch(head map[string][]string) *Req
- func (self *Req) HeadReplace(key string, vals ...string) *Req
- func (self *Req) HeadSet(key, val string) *Req
- func (self *Req) Init() *Req
- func (self *Req) IsReadOnly() bool
- func (self *Req) Join(vals ...interface{}) *Req
- func (self *Req) Json(val interface{}) *Req
- func (self *Req) JsonBytes(val []byte) *Req
- func (self *Req) JsonCatch(val interface{}) (err error)
- func (self *Req) JsonString(val string) *Req
- func (self *Req) Meth(val string) *Req
- func (self *Req) Options() *Req
- func (self *Req) Patch() *Req
- func (self *Req) Path(val string, vals ...interface{}) *Req
- func (self *Req) Post() *Req
- func (self *Req) Put() *Req
- func (self *Req) Query(val map[string][]string) *Req
- func (self *Req) RawQuery(val string) *Req
- func (self *Req) ReadCloser(val io.ReadCloser) *Req
- func (self *Req) Reader(val io.Reader) *Req
- func (self *Req) Req() *http.Request
- func (self *Req) Res() *Res
- func (self *Req) ResCatch() (_ *Res, err error)
- func (self *Req) String(val string) *Req
- func (self *Req) To(src string) *Req
- func (self *Req) Trace() *Req
- func (self *Req) Type(typ string) *Req
- func (self *Req) TypeForm() *Req
- func (self *Req) TypeJson() *Req
- func (self *Req) TypeMulti() *Req
- func (self *Req) Url(val *url.URL) *Req
- func (self *Req) Vals(val map[string][]string) *Req
- func (self *Req) Write(out io.Writer)
- type Res
- func (self *Res) Clone() *Res
- func (self *Res) CloneBody() io.ReadCloser
- func (self *Res) CloseErr() error
- func (self *Res) Done() *Res
- func (self *Res) Dump() *Res
- func (self *Res) Err(desc string) Err
- func (self *Res) Form() url.Values
- func (self *Res) FormCatch() (_ url.Values, err error)
- func (self *Res) IsClientErr() bool
- func (self *Res) IsForm() bool
- func (self *Res) IsInfo() bool
- func (self *Res) IsJson() bool
- func (self *Res) IsMulti() bool
- func (self *Res) IsOk() bool
- func (self *Res) IsRedir() bool
- func (self *Res) IsServerErr() bool
- func (self *Res) Json(out interface{}) *Res
- func (self *Res) JsonCatch(out interface{}) (err error)
- func (self *Res) JsonEither(outVal, outErr interface{}) bool
- func (self *Res) JsonEitherCatch(outVal, outErr interface{}) (_ bool, err error)
- func (self *Res) Loc() string
- func (self *Res) LocUrl() *url.URL
- func (self *Res) LocUrlCatch() (_ *url.URL, err error)
- func (self *Res) Media() (_ string, _ map[string]string)
- func (self *Res) MediaType() (_ string)
- func (self *Res) Ok() *Res
- func (self *Res) OkCatch() (err error)
- func (self *Res) ReadBytes() []byte
- func (self *Res) ReadBytesCatch() (_ []byte, err error)
- func (self *Res) ReadString() string
- func (self *Res) ReadStringCatch() (_ string, err error)
- func (self *Res) Redir() *Res
- func (self *Res) RedirCatch() (err error)
- func (self *Res) Res() *http.Response
- func (self *Res) Type() string
- func (self *Res) Write(out io.Writer)
- func (self *Res) Xml(out interface{}) *Res
- func (self *Res) XmlCatch(out interface{}) (err error)
- func (self *Res) XmlWith(out interface{}, fun func(*xml.Decoder)) *Res
- func (self *Res) XmlWithCatch(out interface{}, fun func(*xml.Decoder)) (err error)
- type StringReadCloser
- type Trans
Examples ¶
Constants ¶
const ( Type = `Content-Type` TypeJson = `application/json` TypeJsonUtf8 = `application/json; charset=utf-8` TypeForm = `application/x-www-form-urlencoded` TypeFormUtf8 = `application/x-www-form-urlencoded; charset=utf-8` TypeMulti = `multipart/form-data` TypeMultiUtf8 = `multipart/form-data; charset=utf-8` )
Variables ¶
This section is empty.
Functions ¶
func ForkReadCloser ¶ added in v0.1.7
func ForkReadCloser(val io.ReadCloser) (_, _ io.ReadCloser)
Fully reads the given stream via `io.ReadAll`, closing it at the end, and returns two "forks". Used internally by `(*gr.Req).CloneBody` and `(*gr.Res).CloneBody`. If reading fails, panics. If the input is nil, both outputs are nil.
func IsClientErr ¶
True if given HTTP status code is between 400 and 499 inclusive.
func IsReadOnly ¶
True if given HTTP method is "", "GET", "HEAD" or "OPTIONS".
func IsServerErr ¶
True if given HTTP status code is between 500 and 599 inclusive.
func Str ¶ added in v0.1.1
func Str(src interface{}) string
Missing feature of the standard library: return a string representation of a primitive or "intentionally" stringable value, without allowing arbitrary non-stringable inputs. Differences from `fmt.Sprint`:
Allow ONLY the following inputs:
nil -> return ""
`fmt.Stringer` -> call `.String()`
Built-in primitive types -> use "strconv"
Automatically dereference pointers to supported types. Nil pointers are considered equivalent to nil.
Panic for all other inputs.
Don't swallow encoding errors.
func UrlAppend ¶ added in v0.1.1
Appends the string representation of the input to the path of the given URL, slash-separated. The input must be string-encodable following the rules of `gr.Str`, and the resulting string must be non-empty, otherwise this panics to safeguard against calling external endpoints on the wrong address. Mutates the given URL and returns it. If the input URL is nil, creates and returns a new non-nil instance. For correctness, you must reassign the output instead of relying on mutation.
func UrlJoin ¶ added in v0.1.1
Appends the string representations of the input values to the path of the given URL, slash-separated. Uses `gr.UrlAppend` for each segment. Each segment must be non-empty, otherwise this panics to safeguard against calling external endpoints on the wrong address. Mutates the given URL and returns it. If the input URL is nil, creates and returns a new non-nil instance. For correctness, you must reassign the output instead of relying on mutation.
Types ¶
type BytesReadCloser ¶
Variant of `bytes.Reader` that also implements nop `io.Closer`. Used internally by `(*gr.Req).Bytes`.
func NewBytesReadCloser ¶
func NewBytesReadCloser(val []byte) *BytesReadCloser
Equivalent to `io.NopCloser(bytes.NewReader(val))`, but avoids 1 indirection and heap allocation by returning `*gr.BytesReadCloser` which implements nop `io.Closer` by itself. Used internally by `(*gr.Req).Bytes`.
type Cli ¶ added in v0.1.3
Short for "client" (not "CLI"). Alias of `http.Client` with added shortcuts for better compatibility with `gr.Req` and `gr.Res`. Freely castable to and from `http.Client`.
func (*Cli) Do ¶ added in v0.1.4
Similar to `(*http.Client).Do`, but with "gr" types. Panics on error. To catch the error, use `(*gr.Cli).DoCatch`.
type Err ¶
type Err struct { Status int `json:"status,omitempty"` Body []byte `json:"body,omitempty"` Cause error `json:"cause,omitempty"` }
Wraps another error, adding an HTTP status code and response body. Some errors returned by this package have codes obtained from `http.Response`.
func (Err) AppendTo ¶ added in v0.1.12
Appends the error representation. Used internally by `.Error`.
func (Err) HttpStatusCode ¶
Returns `.Status`. Implements a hidden interface supported by `github.com/mitranim/rout`.
type Head ¶
Alias of `http.Header`. Provides additional methods. Provides a chainable builder-style API. All methods support both canonical and non-canonical versions of header keys, able to find EXISTING non-canonical entries, canonicalizing them when possible. Freely castable to and from `http.Header`.
func (Head) Add ¶ added in v0.1.1
Similar to `http.Header.Add`, but also looks for an existing entry under this EXACT key, as well as an entry for the canonical version of the key, combining both under the canonical key. Internally calls `append`, which may mutate the backing array of any existing slices for this key. Mutates and returns the receiver. If the receiver is nil, allocates and returns a new map. For correctness, you must always reassign the returned value.
func (Head) Del ¶
Deletes both this exact key and its canonical version. Mutates and returns the receiver.
func (Head) Patch ¶
Applies the patch, using `gr.Head.Replace` for each key-values entry. Mutates and returns the receiver. If the receiver is nil, allocates and returns a new map. For correctness, you must always reassign the returned value.
Accepts an "anonymous" type because all alias types such as `gr.Head` and `http.Header` are automatically castable into it.
func (Head) Replace ¶
Replaces the given key-value, canonicalizing the key. When called with no vals, this is identical to `gr.Head.Del`, deleting the previous entry at BOTH this exact key and its canonical version. When called with some vals, this replaces the previous entry at the canonical version of this key, while deleting the entry at this exact key. The received slice is set as-is, allowing you to reuse a preallocated slice. Mutates and returns the receiver. If the receiver is nil, allocates and returns a new map. For correctness, you must always reassign the returned value.
func (Head) Set ¶
Similar to `http.Header.Set`, but also replaces the previous entry under this exact key, if the key is non-canonical. The resulting entry always has the canonical key. Mutates and returns the receiver. If the receiver is nil, allocates and returns a new map. For correctness, you must always reassign the returned value.
type Req ¶
Alias of `http.Request` with a fluent builder-style API. Freely castable to and from `http.Request`. All methods are defined on `*gr.Req` and may mutate the receiver or its inner references. To store and copy a "partially built" request, use `(*gr.Req).Clone`.
Example (FormBodyPlainResponse) ¶
req := gr.To(testServer.URL).Post().FormVals(url.Values{`one`: {`two`}}) res := req.Res().Ok() defer res.Done() fmt.Printf("\nresponse status: %v\n", res.StatusCode) fmt.Printf("\nresponse type: %v\n", res.Header.Get(gr.Type)) fmt.Printf("\nresponse body:\n%v\n", res.ReadString())
Output: response status: 200 response type: text/plain; charset=utf-8 response body: request method: POST request URL: / request body: one=two
Example (JsonInputJsonOutput) ¶
input := Input{`some input`} var output Output gr.To(testServer.URL).Path(`/json`).Json(input).Res().Ok().Json(&output) fmt.Printf("%#v\n", output)
Output: gr_test.Output{ReqMethod:"GET", ReqUrl:"/json", ReqBody:"{\"inputVal\":\"some input\"}"}
func Connect ¶ added in v0.1.5
func Connect() *Req
Returns a new "CONNECT" request. Shortcut for `new(gr.Req).Connect()`.
func Delete ¶
func Delete() *Req
Returns a new "DELETE" request. Shortcut for `new(gr.Req).Delete()`.
func Init ¶
func Init() *Req
Returns a new request with pre-initialized non-zero context, method, URL, and header. Shortcut for `new(gr.Req).Init()`.
func Options ¶
func Options() *Req
Returns a new "OPTIONS" request. Shortcut for `new(gr.Req).Options()`.
func Path ¶
Returns a new request with the given URL path. Shortcut for `new(gr.Req).Path(val, vals...)`.
func Trace ¶ added in v0.1.5
func Trace() *Req
Returns a new "TRACE" request. Shortcut for `new(gr.Req).Trace()`.
func (*Req) Append ¶ added in v0.1.1
Uses `gr.UrlAppend` to append the input to the URL path, slash-separated. Mutates and returns the receiver.
func (*Req) Bytes ¶
Uses the given chunk as the request body, updating the following fields:
- `.ContentLength` -> input length, in bytes rather than characters.
- `.Body` -> nil or `gr.NewBytesReadCloser` from input.
- `.GetBody` -> nil or function returning `gr.NewBytesReadCloser` from input.
If the input is empty, the listed fields are set to zero values, otherwise the fields are set to non-zero values. Mutates and returns the receiver.
func (*Req) Cli ¶ added in v0.1.3
Sets the given HTTP client, unsafely reusing the `.TLS` field which is normally unused in client requests. Passing nil clears the field. The client is automatically used by `(*gr.Req).Res` and `(*gr.Req).ResCatch`. The name is short for "client", not "CLI". Mutates and returns the receiver.
func (*Req) CliRes ¶
Short for "client response" or "response using client". Performs the request using the given client, returning the response as `*gr.Res`. If the client is nil, uses `http.DefaultClient`. Panics on transport errors, but NOT in case of successful HTTP responses with non-OK HTTP status codes. To avoid panics, use `(*gr.Req).CliResCatch`.
The caller MUST close the response body by calling `*gr.Res.Done` or its other reading or closing methods.
func (*Req) CliResCatch ¶
Variant of `(*gr.Req).CliRes` that returns an error instead of panicking. If the response is non-nil, the caller MUST close the response body by calling `*gr.Res.Done` or its other reading or closing methods.
func (*Req) Client ¶ added in v0.1.3
Returns the HTTP client previously set by `(*gr.Req).Cli`, unsafely reusing the `.TLS` field which is normally unused in client requests. The default is nil.
func (*Req) Clone ¶
Returns a deep copy, like `(*http.Request).Clone`, but without forcing you to provide a context. Cloning allows to reuse partially built requests, like templates. This preserves everything, including the previous context and client. Inner mutable references such as `.URL` and `.Header` are deeply cloned. Unlike `(*http.Request).Clone`, this also clones the body, by calling `(*gr.Req).CloneBody` which is available separately.
func (*Req) CloneBody ¶ added in v0.1.7
func (self *Req) CloneBody() io.ReadCloser
Returns a copy of the request body. Attempts to use `.GetBody` if possible. May fully read, close, and replace the current body. If both `.Body` and `.GetBody` are nil, returns nil.
func (*Req) Context ¶
Returns the inner context as-is. Like `(*http.Request).Context`, but without the hidden fallback on `context.Background`. The function naming is inconsistent with `.Ctx` which sets the context; consistent name would be `.GetCtx` or `.CtxGet`; this name is used to match the existing `(*http.Request).Context`.
func (*Req) Ctx ¶
Sets the inner context to the exact given value, without nil checks or fallbacks. Mutates and returns the receiver.
func (*Req) Dump ¶ added in v0.1.7
Introspection tool. Shortcut for using `(*gr.Req).Write` to dump the request to standard output. Clones before dumping. Can be used in method chains without affecting the original request.
func (*Req) FormVals ¶
URL-encodes the given vals as the request body. Also sets the header "Content-Type: application/x-www-form-urlencoded", as well as fields `.ContentLength` and `.GetBody`. Shortcut for `self.TypeForm().Vals(val)`. Accepts an "anonymous" type because all alias types such as `url.Values` are automatically castable into it. Mutates and returns the receiver.
func (*Req) Head ¶
Sets the given value as `.Header`. Mutates and returns the receiver. Accepts an "anonymous" type because all alias types such as `http.Header` and `gr.Head` are automatically castable into it.
func (*Req) HeadAdd ¶ added in v0.1.1
Appends the given key-value to `.Header` by using `gr.Head.Add`. Allocates the header if necessary. May mutate `.Header` and an existing slice corresponding to the key. Mutates and returns the receiver.
func (*Req) HeadDel ¶
Deletes the given entry in `.Header` by using `gr.Head.Del`. May mutate `.Header`, but not the slices contained therein. Mutates and returns the receiver.
func (*Req) HeadInit ¶ added in v0.1.12
Makes sure `.Header` is non-nil. Mutates and returns the receiver.
func (*Req) HeadPatch ¶
Patches the header by using `gr.Head.Patch`. Allocates the header if necessary. May mutate `.Header`, but not the slices contained therein. Mutates and returns the receiver. Accepts an "anonymous" type because all alias types such as `http.Header` and `gr.Head` are automatically castable into it.
func (*Req) HeadReplace ¶
Replaces the given key-values entry in `.Header` by using `gr.Head.Replace`. Allocates the header if necessary. May mutate `.Header`, but not the slices contained therein. Mutates and returns the receiver.
func (*Req) HeadSet ¶
Sets the given key-value in `.Header` by using `gr.Head.Set`. Allocates the header if necessary. May mutate `.Header`, but not the slices contained therein. Mutates and returns the receiver.
func (*Req) Init ¶
Initializes context, `.Method`, `.URL`, `.Header` to non-zero values, similar to how `http.NewRequest` would have done it. Mutates and returns the receiver.
func (*Req) IsReadOnly ¶
True if `.Method` is "", "GET", "HEAD" or "OPTIONS".
func (*Req) Join ¶ added in v0.1.1
Uses `gr.UrlJoin` to append the inputs to the URL path, slash-separated. Mutates and returns the receiver.
func (*Req) Json ¶
JSON-encodes an arbitrary value, using it as the request body. Also sets the header "Content-Type: application/json", as well as fields `.ContentLength` and `.GetBody`. Panics if JSON encoding fails. Use `(*gr.Req).JsonCatch` to catch those panics. Mutates and returns the receiver.
func (*Req) JsonBytes ¶
Assumes that the given chunk is valid JSON, and uses it as the request body. Also sets "Content-Type: application/json". Shortcut for `self.TypeJson().Bytes(val)`. Mutates and returns the receiver.
func (*Req) JsonCatch ¶
Same as `(*gr.Req).Json`, but if JSON encoding fails, returns an error instead of panicking.
func (*Req) JsonString ¶
Assumes that the given string is valid JSON, and uses it as the request body. Also sets "Content-Type: application/json". Shortcut for `self.TypeJson().String(val)`. Mutates and returns the receiver.
func (*Req) Path ¶
Uses `gr.UrlJoin` to make a URL path and sets the result as `.URL.Path`, creating a new URL reference if the URL was nil. Mutates and returns the receiver.
func (*Req) Query ¶
Shortcut for `self.RawQuery(url.Values(val).Encode())`. Accepts an "anonymous" type because all alias types such as `url.Values` are automatically castable into it.
func (*Req) RawQuery ¶
Sets the given value as `.URL.RawQuery`, creating a new URL reference if the URL was nil. Mutates and returns the receiver.
func (*Req) ReadCloser ¶
func (self *Req) ReadCloser(val io.ReadCloser) *Req
Shortcut for setting `.Body` and returning the request. Sets the body as-is without affecting other fields. Mutates and returns the receiver.
func (*Req) Reader ¶
Sets the given reader as the request body. If the reader is nil, sets nil. Otherwise wraps it in `io.NopCloser`. Mutates and returns the receiver.
func (*Req) Res ¶
Short for "response". Shortcut for `(*gr.Res).CliRes(self.Client())`, which uses `http.DefaultClient` if no client was given. Returns the response as `*gr.Res`. Panics on transport errors, but NOT in case of successful HTTP responses with non-OK HTTP status codes. To avoid panics, use `(*gr.Req).ResCatch`.
The caller MUST close the response body by calling `*gr.Res.Done` or its other reading or closing methods.
func (*Req) ResCatch ¶
Variant of `(*gr.Req).Res` that returns an error instead of panicking. If the response is non-nil, the caller MUST close the response body by calling `*gr.Res.Done` or its other reading or closing methods.
func (*Req) String ¶
Uses the given string as the request body, updating the following fields:
- `.ContentLength` -> input length, in bytes rather than characters.
- `.Body` -> nil or `gr.NewStringReadCloser` from input.
- `.GetBody` -> nil or function returning `gr.NewStringReadCloser` from input.
If the input is empty, the listed fields are set to zero values, otherwise the fields are set to non-zero values. Mutates and returns the receiver.
func (*Req) To ¶
Parses the input via `url.Parse` and sets `.URL` to the result. Panics on parsing errors. Mutates and returns the receiver.
func (*Req) Type ¶
Shortcut for setting the "Content-Type" header. If the input is "", removes the header instead. Mutates and returns the receiver.
func (*Req) TypeForm ¶
Shortcut for setting the "Content-Type: application/x-www-form-urlencoded" header. Mutates and returns the receiver.
func (*Req) TypeJson ¶
Shortcut for setting the "Content-Type: application/json" header. Mutates and returns the receiver.
func (*Req) TypeMulti ¶
Shortcut for setting the "Content-Type: multipart/form-data" header. Mutates and returns the receiver.
func (*Req) Vals ¶
URL-encodes the given vals as the request body. Shortcut for `self.String(url.Values(val).Encode())`. Also sets `.ContentLength` and `.GetBody`. Accepts an "anonymous" type because all alias types such as `url.Values` are automatically castable into it. Mutates and returns the receiver.
type Res ¶
Alias of `http.Response` with many shortcuts for inspecting and decoding the response. Freely castable to and from `http.Response`.
When using `gr`, a response can be obtained by calling `(*gr.Req).Res` or `(*gr.Req).CliRes`. However, this is also usable for responses obtained from other sources. You can cast any `*http.Response` to `*gr.Res` to simplify its inspection and decoding.
The caller MUST close the response body by calling `(*gr.Res).Done` or its other reading or closing methods.
func (*Res) Clone ¶ added in v0.1.7
Similar to `(*gr.Res).Clone`. Returns a deep copy whose mutations don't affect the original. Mostly useful for introspection, like dumping to standard output, which requires reading the body. Clones the body via `(*gr.Res).CloneBody` which is available separately, and other fields via their standard library counterparts.
func (*Res) CloneBody ¶ added in v0.1.7
func (self *Res) CloneBody() io.ReadCloser
Returns a copy of the response body. Mutates the receiver by fully reading, closing, and replacing the current body. If the current body is nil, this is a nop and the output is nil.
func (*Res) Done ¶
Closes the response body if possible, returning the same response. Can be deferred or used in method chains.
func (*Res) Dump ¶ added in v0.1.7
Introspection tool. Shortcut for using `(*gr.Res).Write` to dump the response to standard output. Clones before dumping. Can be used in method chains without affecting the original response.
func (*Res) Err ¶ added in v0.1.5
Returns an error that includes the response HTTP status code and the downloaded body, as well as the provided short description. Always downloads and closes the response body, if any. The description must be non-empty, and represent a reason why the response is unsatisfactory, such as "non-OK" or "non-redirect".
func (*Res) Form ¶
Downloads the response body and parses it as URL-encoded/form-encoded content, using `url.ParseQuery`. Returns the parsed result. Panics if body can't be read, or if parsing fails. Always closes the body.
func (*Res) FormCatch ¶
Non-panicking version of `(*gr.Res).Form`. If body can't be read, or if parsing fails, returns an error. Always closes the body.
func (*Res) IsClientErr ¶
True if response status code is between 400 and 499 inclusive.
func (*Res) IsForm ¶ added in v0.1.9
True if the parsed media type of `Content-Type` is `gr.TypeForm`.
func (*Res) IsJson ¶ added in v0.1.9
True if the parsed media type of `Content-Type` is `gr.TypeJson`.
func (*Res) IsMulti ¶ added in v0.1.9
True if the parsed media type of `Content-Type` is `gr.TypeMulti`.
func (*Res) IsServerErr ¶
True if response status code is between 500 and 599 inclusive.
func (*Res) Json ¶
Parses the response body into the given output, which must be either nil or a pointer. Uses `json.Decoder` to decode from a stream, without buffering the entire body. Panics on errors. If the output is nil, skips downloading or decoding. Returns the same response. Always closes the body.
func (*Res) JsonCatch ¶
Non-panicking version of `(*gr.Res).Json`. Returns an error if body downloading or parsing fails. Always closes the body.
func (*Res) JsonEither ¶
If the response is "ok", decodes the response body into `outVal`. Otherwise decodes the response body into `outErr`. Both outputs are optional; if the relevant output is nil, skips downloading and decoding. Returns true if the response is "ok", and false if not. Panics on downloading or decoding errors. Always closes the body.
func (*Res) JsonEitherCatch ¶
Non-panicking version of `(*gr.Res).JsonEither`. If body can't be read, or if parsing fails, returns an error. Always closes the body.
func (*Res) Loc ¶
Short for "location". Returns the response header "Location". Sometimes useful when inspecting redirect responses.
func (*Res) LocUrl ¶
Short for "location URL". Parses the response header "Location" and returns it as URL. If parsing fails, panics with a descriptive error.
func (*Res) LocUrlCatch ¶
Non-panicking version of `(*gr.Res).LocUrl`. Returns a parsed redirect location or a descriptive parse error.
func (*Res) Media ¶ added in v0.1.9
Parses the `Content-Type` header via `mime.ParseMediaType`. Panics on error.
func (*Res) Ok ¶
Asserts that the response is "ok". If not "ok", panics with an error that includes the response body as text, and closes the body. If "ok", returns the response unchanged without closing the body.
func (*Res) OkCatch ¶
Non-panicking version of `(*gr.Res).Ok`. If not "ok", returns an error that includes the response body as text, and closes the body. Otherwise returns nil without closing the body.
func (*Res) ReadBytes ¶
Uses `io.ReadAll` to read the entire response body, returning the resulting chunk. Panics if reading can't be completed. Always closes the body.
func (*Res) ReadBytesCatch ¶
Non-panicking version of `(*gr.Res).ReadBytes`. If body reading fails, returns an error. Always closes the body.
func (*Res) ReadString ¶
Similar to `(*gr.Res).ReadBytes`, but returns the entire response body as a string, without copying. Always closes the body.
func (*Res) ReadStringCatch ¶
Non-panicking version of `(*gr.Res).ReadString`. If body reading fails, returns an error. Always closes the body.
func (*Res) Redir ¶
Asserts that the response is a redirect. If not a redirect, panics with an error that includes the response body as text, and closes the body. If a redirect, returns the response unchanged without closing the body.
func (*Res) RedirCatch ¶
Non-panicking version of `(*gr.Res).Redir`. If not a redirect, returns an error that includes the response body as text, and closes the body. Otherwise returns nil without closing the body.
func (*Res) Type ¶ added in v0.1.9
Returns the `Content-Type` header. Note that the content-type may contain additional parameters, and needs to be parsed before comparing it to a "pure" media type such as `gr.TypeJson`.
func (*Res) Write ¶ added in v0.1.7
Introspection shortcut. Uses `(*http.Response).Write`, but panics on error instead of returning an error. Follows the write with a newline. Caution: mutates the response by reading the body. If you intend to further read the response, use `.Clone` or `.Dump`.
func (*Res) Xml ¶
Shortcut for `(*gr.Res).XmlWith` with a nil func. Decodes the response body without any special XML decoder options.
func (*Res) XmlCatch ¶
Non-panicking version of `(*gr.Res).Xml`. Returns an error if body downloading or parsing fails. Always closes the body.
func (*Res) XmlWith ¶ added in v0.1.8
Parses the response body into the given output, which must be either nil or a pointer. Uses `xml.Decoder` to decode from a stream, without buffering the entire body. The given function is used to customize the decoder, and may be nil. Panics on errors. If the output is nil, skips downloading or decoding. Returns the same response. Always closes the body.
type StringReadCloser ¶
Variant of `strings.Reader` that also implements nop `io.Closer`. Used internally by `(*gr.Req).String`.
func NewStringReadCloser ¶
func NewStringReadCloser(val string) *StringReadCloser
Equivalent to `io.NopCloser(strings.NewReader(val))`, but avoids 1 indirection and heap allocation by returning `*gr.StringReadCloser` which implements nop `io.Closer` by itself. Used internally by `(*gr.Req).String`.