Documentation ¶
Overview ¶
Package httpclient provides the basic infrastructure for doing RESTish http requests an application specific client will be generated with the client-gen-go tool.
Index ¶
- Constants
- Variables
- func MarshalJSON(w io.Writer, v interface{}, mediaType string) error
- func MarshalYAML(w io.Writer, v interface{}, mediaType string) error
- func QueryOptions(u string, opt interface{}) (string, error)
- func UnmarshalJSON(r io.Reader, v interface{}, mediaType string) error
- func UnmarshalYAML(r io.Reader, v interface{}, mediaType string) error
- type Client
- type MarshalerFunc
- type Opt
- type RequestCallbackFunc
- type ResponseCallbackFunc
- type UnmarshalerFunc
Examples ¶
Constants ¶
const ( ContentTypeText = "text/plain" ContentTypeJSON = "application/json" ContentTypeYAML = "application/yaml" )
Constants
Variables ¶
var ( ErrUnknownContentType = errors.New("unknown media type") ErrTooManyRequest = errors.New("too many requests") )
Variables
Functions ¶
func MarshalJSON ¶
MarshalJSON marshal JSON
func MarshalYAML ¶
MarshalYAML marshal JSON
func QueryOptions ¶
QueryOptions adds query options opt to URL u opt has to be a struct tagged according to https://github.com/google/go-querystring e.g.:
type options struct { Page int `url:"page,omitempty"` PerPage int `url:"per_page,omitempty"` Search string `url:"search,omitempty"` }
opt := options{1, 10, "name=testHost"} ... will be added to URL u as "?page=1&per_page=10&search=name%3DtestHost"
func UnmarshalJSON ¶
UnmarshalJSON unmarshal JSON
Types ¶
type Client ¶
type Client struct { // Base URL for API requests. BaseURL *url.URL // ContentType is used as Content-Type and Accept in request headers. ContentType string Marshaler MarshalerFunc Unmarshaler UnmarshalerFunc RequestCallback RequestCallbackFunc ResponseCallback ResponseCallbackFunc // contains filtered or unexported fields }
Client provides ....
func (*Client) Do ¶
Do sends an API request and returns the API response. The API response will be decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response will be written to v, without attempting to decode it.
func (*Client) NewRequest ¶
NewRequest creates an API request. A relative URL can be provided in urlStr, which will be resolved to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body will be encoded and included in as the request body.
type MarshalerFunc ¶
MarshalerFunc for custom marshaling function
type Opt ¶
Opt are options for New.
func WithContentType ¶
WithContentType is a client option for setting the content type
func WithHTTPClient ¶
WithHTTPClient is a client option for setting another http client than the default one
func WithHeader ¶ added in v0.1.1
WithHeader is a client option for setting custom http header(s) for each request Content-Type and Accept headers will be appended by the clients ContentType setting Authorization header is overwritten if WithUsername/WithPassowrd was used to setup the client
func WithPassword ¶
WithPassword is a client option for setting the password for basic authentication.
func WithRateLimiter ¶
WithRateLimiter see https://godoc.org/golang.org/x/time/rate
func WithUsername ¶
WithUsername is a client option for setting the username.
type RequestCallbackFunc ¶
RequestCallbackFunc for custom pre-processing of requests possible use cases: custom error checking, dumping requests for debugging etc.
Example ¶
This example shows how the RequestCallback function can be used to dump requests. Any pre-processing of requests would be possible using RequestCallback (eg. custom error checking).
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/example" { http.Error(w, "invalid", http.StatusNotFound) return } })) defer ts.Close() c, _ := New(ts.URL) // Overwrite the clients standard RequestCallback function with our custom function which dumps // some information for each request (r) to os.Stdout and returns the unmodified request. // Clients functionality is not affected by this, because the standard requestCallback function of // the client just returns the unmodified request (r). c.RequestCallback = func(r *http.Request) *http.Request { // to convert the request in an appropriate curl command // command, _ := http2curl.GetCurlCommand(r) fmt.Fprintf(os.Stdout, "Accept: %s\nContent-Type: %s\nMethod: %s", r.Header.Get("Accept"), r.Header.Get("Content-Type"), r.Method) return r } req, _ := c.NewRequest(http.MethodGet, "/example", nil) resp, _ := c.Do(context.Background(), req, nil) if resp != nil && resp.Body != nil { _ = resp.Body.Close() }
Output: Accept: application/json Content-Type: application/json Method: GET
type ResponseCallbackFunc ¶
ResponseCallbackFunc for custom post-processing of responses possible use cases: custom error checking, dumping responses for debugging etc.
Example ¶
This example shows how the ResponseCallback function can be used to dump responses. Any post-processing of responses would be possible using ResponseCallback (eg. custom error checking).
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/example" { http.Error(w, "invalid", http.StatusNotFound) return } // check post data body, _ := ioutil.ReadAll(r.Body) _, _ = w.Write(body) })) defer ts.Close() c, _ := New(ts.URL) type message struct { Text string } // Overwrite the clients standard ResponseCallback function with our custom function which dumps // some information for each response (r) to os.Stdout. // IMPORTANT: The clients standard responseCallback function returns an error if // http.StatusCode is outside of the 200 range. If you want to preserve the standard functionality consider adding the // if statement shown in this example. c.ResponseCallback = func(r *http.Response) (*http.Response, error) { // save the body of the response, because we consume it here but still want to return it to the caller var save io.ReadCloser save, r.Body, _ = drainBody(r.Body) body, _ := ioutil.ReadAll(r.Body) // print and then restore the body fmt.Fprintf(os.Stdout, "%s", body) r.Body = save // important to preserve standard clients behaviur if c := r.StatusCode; c >= 200 && c <= 299 { return r, nil } return r, errors.New(r.Status) } req, _ := c.NewRequest(http.MethodPost, "/example", &message{Text: "example"}) resp, _ := c.Do(context.Background(), req, nil) if resp != nil && resp.Body != nil { _ = resp.Body.Close() }
Output: {"Text":"example"}
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
example
|
|
jsonplaceholder
Package jsonplaceholder implements an example httpclient
|
Package jsonplaceholder implements an example httpclient |