Documentation
¶
Overview ¶
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/worldline-go/klient"
)
type Client struct {
klient *klient.Client
}
func (c *Client) CreateX(ctx context.Context, r CreateXRequest) (*CreateXResponse, error) {
var v CreateXResponse
if err := c.klient.DoWithFunc(ctx, r, func(r *http.Response) error {
if r.StatusCode != http.StatusOK {
return klient.UnexpectedResponseError(r)
}
if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return &v, nil
}
// ----
type CreateXRequest struct {
ID string `json:"id"`
}
func (CreateXRequest) Method() string {
return http.MethodPost
}
func (CreateXRequest) Path() string {
return "/api/v1/x"
}
func (r CreateXRequest) BodyJSON() interface{} {
return r
}
func (r CreateXRequest) Validate() error {
if r.ID == "" {
return fmt.Errorf("id is required")
}
return nil
}
func (r CreateXRequest) Header() http.Header {
v := http.Header{}
v.Set("X-Info", "example")
return v
}
type CreateXResponse struct {
RequestID string `json:"request_id"`
}
// ---
func main() {
httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check request method
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "invalid request method"}`))
return
}
// check request path
if r.URL.Path != "/api/v1/x" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "invalid request path"}`))
return
}
// check request header
if r.Header.Get("X-Info") != "example" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "invalid request header"}`))
return
}
// get request body
var m map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "invalid request body"}`))
return
}
// check request body
if m["id"] != "123" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "invalid id"}`))
return
}
// write response
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"request_id": "123+"}`))
}))
defer httpServer.Close()
httpxClient, err := klient.New(
klient.OptionClient.WithBaseURL(httpServer.URL),
)
if err != nil {
fmt.Println(err)
return
}
c := &Client{
klient: httpxClient,
}
v, err := c.CreateX(context.Background(), CreateXRequest{
ID: "123",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v.RequestID)
}
Output: 123+
Index ¶
- Variables
- func LimitedResponse(resp *http.Response) []byte
- func NewRetryPolicy(opts ...OptionRetryFn) retryablehttp.CheckRetry
- func Request(ctx context.Context, baseURL, method, path string, body io.Reader, ...) error
- func RetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error)
- func UnexpectedResponse(resp *http.Response) error
- func UnexpectedResponseError(resp *http.Response) error
- type Client
- type InfBody
- type InfBodyJSON
- type InfHeader
- type InfQueryStringGenerator
- type InfRequest
- type InfRequestValidator
- type Null
- type OptionClientFn
- type OptionClientHolder
- func (OptionClientHolder) WithBackoff(backoff retryablehttp.Backoff) OptionClientFn
- func (OptionClientHolder) WithBaseURL(baseURL string) OptionClientFn
- func (OptionClientHolder) WithCtx(ctx context.Context) OptionClientFn
- func (OptionClientHolder) WithDisableBaseURLCheck(baseURLCheck bool) OptionClientFn
- func (OptionClientHolder) WithDisableRetry(disableRetry bool) OptionClientFn
- func (OptionClientHolder) WithHTTPClient(httpClient *http.Client) OptionClientFn
- func (OptionClientHolder) WithInsecureSkipVerify(insecureSkipVerify bool) OptionClientFn
- func (OptionClientHolder) WithLogger(logger zerolog.Logger) OptionClientFn
- func (OptionClientHolder) WithMaxConnections(maxConnections int) OptionClientFn
- func (OptionClientHolder) WithPooledClient(pooledClient bool) OptionClientFn
- func (OptionClientHolder) WithRetryLog(retryLog bool) OptionClientFn
- func (OptionClientHolder) WithRetryMax(retryMax int) OptionClientFn
- func (OptionClientHolder) WithRetryOptions(opts ...OptionRetryFn) OptionClientFn
- func (OptionClientHolder) WithRetryPolicy(retryPolicy retryablehttp.CheckRetry) OptionClientFn
- func (OptionClientHolder) WithRetryWaitMax(retryWaitMax time.Duration) OptionClientFn
- func (OptionClientHolder) WithRetryWaitMin(retryWaitMin time.Duration) OptionClientFn
- func (OptionClientHolder) WithTransportWrapper(f func(context.Context, http.RoundTripper) (http.RoundTripper, error)) OptionClientFn
- type OptionRetryFn
- type OptionRetryHolder
- func (OptionRetryHolder) WithOptionRetry(oRetry *OptionRetryValue) OptionRetryFn
- func (OptionRetryHolder) WithRetryDisable() OptionRetryFn
- func (OptionRetryHolder) WithRetryDisabledStatusCodes(codes ...int) OptionRetryFn
- func (OptionRetryHolder) WithRetryEnabledStatusCodes(codes ...int) OptionRetryFn
- func (OptionRetryHolder) WithRetryLog(log logz.Adapter) OptionRetryFn
- type OptionRetryValue
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrValidating = fmt.Errorf("failed to validate request") ErrMarshal = fmt.Errorf("failed to marshal request body") ErrRequest = fmt.Errorf("failed to do request") ErrResponseFuncNil = fmt.Errorf("response function is nil") )
var OptionClient = OptionClientHolder{}
var OptionRetry = OptionRetryHolder{}
var ResponseErrLimit int64 = 1 << 20 // 1MB
Functions ¶
func LimitedResponse ¶
LimitedResponse not close body, retry library draining it.
func NewRetryPolicy ¶
func NewRetryPolicy(opts ...OptionRetryFn) retryablehttp.CheckRetry
func Request ¶
func Request(ctx context.Context, baseURL, method, path string, body io.Reader, header http.Header, fn func(*http.Response) error) error
Request sends an HTTP request and calls the response function with the global client.
func RetryPolicy ¶
RetryPolicy provides a default callback for Client.CheckRetry, which will retry on connection errors and server errors.
func UnexpectedResponse ¶
UnexpectedResponse returns an error if the response status code is not 2xx.
func UnexpectedResponseError ¶
UnexpectedResponseError returns an error with the response body.
Types ¶
type Client ¶
type Client struct {
HTTPClient *http.Client
BaseURL *url.URL
// contains filtered or unexported fields
}
func New ¶
func New(opts ...OptionClientFn) (*Client, error)
New creates a new http client with the provided options.
Default BaseURL is required, it can be disabled by setting DisableBaseURLCheck to true.
func (*Client) Do ¶
func (c *Client) Do(ctx context.Context, req InfRequest, resp interface{}) error
Do sends an HTTP request and json unmarshals the response body to data.
Do work same as DoWithFunc with defaultResponseFunc.
func (*Client) DoWithFunc ¶
func (c *Client) DoWithFunc(ctx context.Context, req InfRequest, fn func(*http.Response) error) error
DoWithFunc sends an HTTP request and calls the response function.
Request additional implements InfRequestValidator, InfQueryStringGenerator, InfHeader, InfBody, InfBodyJSON.
type InfBodyJSON ¶
type InfBodyJSON interface {
// BodyJSON can return any type that can be marshaled to JSON.
// Automatically sets Content-Type to application/json.
BodyJSON() interface{}
}
type InfQueryStringGenerator ¶
type InfRequest ¶
type InfRequest interface {
// Method returns the HTTP method.
Method() string
// Path returns the path to be sent.
Path() string
}
InfRequest is the base interface for all requests.
type InfRequestValidator ¶
type InfRequestValidator interface {
// Validate returns error if request is invalid.
Validate() error
}
type OptionClientFn ¶ added in v0.1.2
type OptionClientFn func(*optionClientValue)
OptionClientFn is a function that configures the client.
type OptionClientHolder ¶ added in v0.1.1
type OptionClientHolder struct{}
func (OptionClientHolder) WithBackoff ¶ added in v0.1.1
func (OptionClientHolder) WithBackoff(backoff retryablehttp.Backoff) OptionClientFn
WithBackoff configures the client to use the provided backoff.
func (OptionClientHolder) WithBaseURL ¶ added in v0.1.1
func (OptionClientHolder) WithBaseURL(baseURL string) OptionClientFn
WithBaseURL configures the client to use the provided base URL.
func (OptionClientHolder) WithCtx ¶ added in v0.1.1
func (OptionClientHolder) WithCtx(ctx context.Context) OptionClientFn
WithCtx for TransportWrapper call.
func (OptionClientHolder) WithDisableBaseURLCheck ¶ added in v0.1.1
func (OptionClientHolder) WithDisableBaseURLCheck(baseURLCheck bool) OptionClientFn
WithDisableBaseURLCheck configures the client to disable base URL check.
func (OptionClientHolder) WithDisableRetry ¶ added in v0.1.1
func (OptionClientHolder) WithDisableRetry(disableRetry bool) OptionClientFn
WithDisableRetry configures the client to disable retry.
func (OptionClientHolder) WithHTTPClient ¶ added in v0.1.1
func (OptionClientHolder) WithHTTPClient(httpClient *http.Client) OptionClientFn
WithHTTPClient configures the client to use the provided http client.
func (OptionClientHolder) WithInsecureSkipVerify ¶ added in v0.1.1
func (OptionClientHolder) WithInsecureSkipVerify(insecureSkipVerify bool) OptionClientFn
WithInsecureSkipVerify configures the client to skip TLS verification.
func (OptionClientHolder) WithLogger ¶ added in v0.1.1
func (OptionClientHolder) WithLogger(logger zerolog.Logger) OptionClientFn
WithLogger configures the client to use the provided logger.
func (OptionClientHolder) WithMaxConnections ¶ added in v0.1.1
func (OptionClientHolder) WithMaxConnections(maxConnections int) OptionClientFn
WithMaxConnections configures the client to use the provided maximum number of idle connections.
func (OptionClientHolder) WithPooledClient ¶ added in v0.1.1
func (OptionClientHolder) WithPooledClient(pooledClient bool) OptionClientFn
func (OptionClientHolder) WithRetryLog ¶ added in v0.1.1
func (OptionClientHolder) WithRetryLog(retryLog bool) OptionClientFn
WithRetryLog configures the client to use the provided retry log flag, default is true.
This option is only used with default retry policy.
func (OptionClientHolder) WithRetryMax ¶ added in v0.1.1
func (OptionClientHolder) WithRetryMax(retryMax int) OptionClientFn
WithRetryMax configures the client to use the provided maximum number of retry.
func (OptionClientHolder) WithRetryOptions ¶ added in v0.1.1
func (OptionClientHolder) WithRetryOptions(opts ...OptionRetryFn) OptionClientFn
func (OptionClientHolder) WithRetryPolicy ¶ added in v0.1.1
func (OptionClientHolder) WithRetryPolicy(retryPolicy retryablehttp.CheckRetry) OptionClientFn
WithRetryPolicy configures the client to use the provided retry policy.
func (OptionClientHolder) WithRetryWaitMax ¶ added in v0.1.1
func (OptionClientHolder) WithRetryWaitMax(retryWaitMax time.Duration) OptionClientFn
WithRetryWaitMax configures the client to use the provided maximum wait time.
func (OptionClientHolder) WithRetryWaitMin ¶ added in v0.1.1
func (OptionClientHolder) WithRetryWaitMin(retryWaitMin time.Duration) OptionClientFn
WithRetryWaitMin configures the client to use the provided minimum wait time.
func (OptionClientHolder) WithTransportWrapper ¶ added in v0.1.1
func (OptionClientHolder) WithTransportWrapper(f func(context.Context, http.RoundTripper) (http.RoundTripper, error)) OptionClientFn
WithTransportWrapper configures the client to wrap the default transport.
type OptionRetryFn ¶ added in v0.1.2
type OptionRetryFn func(*optionRetryValue)
type OptionRetryHolder ¶ added in v0.1.1
type OptionRetryHolder struct{}
func (OptionRetryHolder) WithOptionRetry ¶ added in v0.1.1
func (OptionRetryHolder) WithOptionRetry(oRetry *OptionRetryValue) OptionRetryFn
WithOptionRetry configures the retry policy directly.
This option overrides all other retry options when previously set.
func (OptionRetryHolder) WithRetryDisable ¶ added in v0.1.1
func (OptionRetryHolder) WithRetryDisable() OptionRetryFn
func (OptionRetryHolder) WithRetryDisabledStatusCodes ¶ added in v0.1.1
func (OptionRetryHolder) WithRetryDisabledStatusCodes(codes ...int) OptionRetryFn
func (OptionRetryHolder) WithRetryEnabledStatusCodes ¶ added in v0.1.1
func (OptionRetryHolder) WithRetryEnabledStatusCodes(codes ...int) OptionRetryFn
func (OptionRetryHolder) WithRetryLog ¶ added in v0.1.1
func (OptionRetryHolder) WithRetryLog(log logz.Adapter) OptionRetryFn
type OptionRetryValue ¶
type OptionRetryValue = optionRetryValue