httpclient

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2022 License: MIT Imports: 14 Imported by: 3

README

Go Report Card GoDoc Build Status Coverage Status

httpclient

Generates a HTTP client from a service definition (interface). The created client is ready to use in production with many configuration options and sensible defaults.

Requirements

Go 1.7

Installation

# go get -u github.com/postfinance/httpclient/cmd/httpclient-gen-go

Usage

See example

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

Examples

Constants

View Source
const (
	ContentTypeText = "text/plain"
	ContentTypeJSON = "application/json"
	ContentTypeYAML = "application/yaml"
)

Constants

Variables

View Source
var (
	ErrUnknownContentType = errors.New("unknown media type")
	ErrTooManyRequest     = errors.New("too many requests")
)

Variables

Functions

func MarshalJSON

func MarshalJSON(w io.Writer, v interface{}, mediaType string) error

MarshalJSON marshal JSON

func MarshalYAML

func MarshalYAML(w io.Writer, v interface{}, mediaType string) error

MarshalYAML marshal JSON

func QueryOptions

func QueryOptions(u string, opt interface{}) (string, error)

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

func UnmarshalJSON(r io.Reader, v interface{}, mediaType string) error

UnmarshalJSON unmarshal JSON

func UnmarshalYAML

func UnmarshalYAML(r io.Reader, v interface{}, mediaType string) error

UnmarshalYAML unmarshal YAML

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 New

func New(baseURL string, opts ...Opt) (*Client, error)

New returns a new client instance.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error)

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

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

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

type MarshalerFunc func(io.Writer, interface{}, string) (string, error)

MarshalerFunc for custom marshaling function

type Opt

type Opt func(*Client) error

Opt are options for New.

func WithContentType

func WithContentType(ct string) Opt

WithContentType is a client option for setting the content type

func WithHTTPClient

func WithHTTPClient(c *http.Client) Opt

WithHTTPClient is a client option for setting another http client than the default one

func WithHeader added in v0.1.1

func WithHeader(header http.Header) Opt

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

func WithPassword(p string) Opt

WithPassword is a client option for setting the password for basic authentication.

func WithRateLimiter

func WithRateLimiter(l *rate.Limiter) Opt

WithRateLimiter see https://godoc.org/golang.org/x/time/rate

func WithUsername

func WithUsername(u string) Opt

WithUsername is a client option for setting the username.

type RequestCallbackFunc

type RequestCallbackFunc func(*http.Request) *http.Request

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

type ResponseCallbackFunc func(*http.Response) (*http.Response, error)

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"}

type UnmarshalerFunc

type UnmarshalerFunc func(io.Reader, interface{}, string) error

UnmarshalerFunc for custom unmarshaling function

Directories

Path Synopsis
cmd
example
jsonplaceholder
Package jsonplaceholder implements an example httpclient
Package jsonplaceholder implements an example httpclient

Jump to

Keyboard shortcuts

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