Documentation
¶
Index ¶
- func BindResponseBody(resp *http.Response, target any) error
- func CodecForRequest(r *http.Request, name ...string) (encoding.Codec, bool)
- func CodecForResponse(r *http.Response, name ...string) (encoding.Codec, bool)
- func CodecForString(contentType string) encoding.Codec
- func EncodeRequestBody(req *http.Request, body any) error
- func ForceHttps(endpoint string) string
- func IsTimeout(err error) bool
- func ProxyURL(address string) func(*http.Request) (*url.URL, error)
- func RegisterCodec(contentType string, codec encoding.Codec)
- func RegisterCodecName(contentType string, name string)
- func SetQuery(req *http.Request, q any) error
- func SetRequestBody(req *http.Request, body io.Reader) error
- func StatusForErr(err error) (int, bool)
- type CallOption
- type CallOptions
- type Client
- type ClientOption
- func WithContentType(contentType string) ClientOption
- func WithDebug(open bool) ClientOption
- func WithDebugInterface(f func() DebugInterface) ClientOption
- func WithEndpoint(endpoint string) ClientOption
- func WithLimiter(l Limiter) ClientOption
- func WithNot2xxError(f func() error) ClientOption
- func WithProxy(f func(*http.Request) (*url.URL, error)) ClientOption
- func WithTLSConfig(cfg *tls.Config) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- func WithTransport(transport http.RoundTripper) ClientOption
- func WithUserAgent(userAgent string) ClientOption
- type Debug
- type DebugInterface
- type Error
- type Limiter
- type RequestFunc
- type ResponseFunc
- type TraceInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindResponseBody ¶
BindResponseBody binds the body of an HTTP response to the given 'target' struct, automatically decoding the body based on the Content-Type header of the response.
This function checks the Content-Type header and decodes the response body into the corresponding Go type. It assumes that the 'target' parameter is a pointer to the structure that should be populated with the response data.
Example usage:
var userResponse User
err := BindResponseBody(response, &userResponse)
if err != nil {
log.Fatal("Failed to bind response body:", err)
}
// The 'userResponse' struct will now be populated with the decoded response data.
func CodecForRequest ¶
CodecForRequest get encoding.Codec via http.Request
func CodecForResponse ¶
CodecForResponse get encoding.Codec via http.Response
func CodecForString ¶
CodecForString get encoding.Codec via string
func EncodeRequestBody ¶
EncodeRequestBody encodes the provided body content based on the Content-Type of the given HTTP request, and sets the encoded body in the request.
The function will automatically detect the Content-Type header of the request and encode the body accordingly (e.g., JSON, XML, etc.). It then uses SetRequestBody to set the encoded body in the request.
Example usage:
// Example structure to be encoded into the request body
type MyRequest struct {
Name string `json:"name"`
Value int `json:"value"`
}
req, err := http.NewRequest("POST", "https://example.com/api", nil)
if err != nil {
log.Fatal("Failed to create request:", err)
}
body := MyRequest{Name: "example", Value: 42}
err = EncodeRequestBody(req, body)
if err != nil {
log.Fatal("Failed to encode request body:", err)
}
// Now the request body is set to the JSON-encoded version of MyRequest
fmt.Println("Request prepared with body:", req.Body)
func ForceHttps ¶
ForceHttps ensures that the provided endpoint is using the HTTPS protocol. It checks if the URL already contains a scheme (like "http://"), removes it, and then prepends "https://" to the endpoint to ensure the URL uses HTTPS.
Example usage:
url := "http://example.com" secureUrl := ForceHttps(url) fmt.Println(secureUrl) // Output: "https://example.com"
func ProxyURL ¶
ProxyURL returns a function that sets a proxy URL for the given HTTP request.
This function accepts an address as input and ensures that the address is properly formatted as a valid URL. If the address is a relative address (e.g., ":7890" or "/proxy"), it is converted to a full HTTP address (e.g., "http://127.0.0.1:7890"). If the address does not include a scheme (e.g., "http://"), the function prepends "http://" to the address. The returned function can be used to configure HTTP requests to route through the specified proxy.
func RegisterCodec ¶
func RegisterCodecName ¶
func SetQuery ¶
SetQuery encodes the provided query parameters into a URL query string and appends them to the given HTTP request's URL. This function uses the `github.com/nexuer/ghttp/query` package to encode the query parameters. The query parameters are serialized into the URL query string format and appended to the existing URL of the HTTP request. If the request already contains a query string, the new parameters will be appended to it. If no query parameters are provided, no changes are made to the request.
Example usage:
req, err := http.NewRequest("GET", "https://example.com/api", nil)
if err != nil {
log.Fatal("Failed to create request:", err)
}
// Define query parameters as a struct
queryParams := struct {
Name string `query:"name"`
Value int `query:"value"`
}{
Name: "example",
Value: 42,
}
err = SetQuery(req, queryParams)
if err != nil {
log.Fatal("Failed to set query parameters:", err)
}
// The request URL will now include the query parameters encoded as `?name=example&value=42`
func SetRequestBody ¶
SetRequestBody modifies the body of the given HTTP request.
This function allows you to set or replace the body of the HTTP request with the provided 'body' parameter. The body is expected to be an io.Reader, which means it can be any type that implements the io.Reader interface, such as a byte buffer or a file stream.
Example usage:
req, err := http.NewRequest("POST", "https://example.com", nil)
if err != nil {
log.Fatal("Failed to create request:", err)
}
body := strings.NewReader("some request data")
err = SetRequestBody(req, body)
if err != nil {
log.Fatal("Failed to set request body:", err)
}
// Now the request body is set to "some request data"
func StatusForErr ¶
Types ¶
type CallOption ¶
type CallOption interface {
Before(request *http.Request) error
After(response *http.Response) error
}
func After ¶
func After(hooks ...ResponseFunc) CallOption
func BasicAuth ¶
func BasicAuth(username, password string) CallOption
func BearerToken ¶
func BearerToken(token string) CallOption
func Before ¶
func Before(hooks ...RequestFunc) CallOption
func Query ¶
func Query(q any) CallOption
type CallOptions ¶
type CallOptions struct {
// Set query parameters
Query any
// Basic auth
Username string
Password string
// Bearer token
BearerToken string
// hooks
BeforeHooks []RequestFunc
AfterHooks []ResponseFunc
}
CallOptions default call options
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client.
func NewClient ¶
func NewClient(opts ...ClientOption) *Client
func (*Client) SetEndpoint ¶
type ClientOption ¶
type ClientOption func(*clientOptions)
ClientOption is HTTP client option.
func WithContentType ¶
func WithContentType(contentType string) ClientOption
WithContentType with client request content type.
func WithDebugInterface ¶
func WithDebugInterface(f func() DebugInterface) ClientOption
WithDebugInterface sets the function to create a new DebugInterface instance.
func WithLimiter ¶
func WithLimiter(l Limiter) ClientOption
WithLimiter sets a rate limiter for the client. This limiter will be applied to control the number of requests made to the server, ensuring that the requests stay within the specified limits.
func WithNot2xxError ¶
func WithNot2xxError(f func() error) ClientOption
WithNot2xxError handle response status code < 200 and code > 299
func WithTLSConfig ¶
func WithTLSConfig(cfg *tls.Config) ClientOption
WithTLSConfig with tls config.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout with client request timeout.
func WithTransport ¶
func WithTransport(transport http.RoundTripper) ClientOption
WithTransport with http.RoundTrippe.
func WithUserAgent ¶
func WithUserAgent(userAgent string) ClientOption
WithUserAgent with client user agent.
type Debug ¶
type Debug struct {
Writer io.Writer
Trace bool
TraceCallback func(w io.Writer, info TraceInfo)
// contains filtered or unexported fields
}
type DebugInterface ¶
type RequestFunc ¶
type ResponseFunc ¶
type TraceInfo ¶
type TraceInfo struct {
DNSDuration time.Duration `json:"DNSDuration,omitempty" yaml:"DNSDuration" xml:"DNSDuration"`
ConnectDuration time.Duration `json:"connectDuration,omitempty" yaml:"connectDuration" xml:"connectDuration"`
TLSHandshakeDuration time.Duration `json:"TLSHandshakeDuration,omitempty" yaml:"TLSHandshakeDuration" xml:"TLSHandshakeDuration"`
RequestDuration time.Duration `json:"requestDuration,omitempty" yaml:"requestDuration" xml:"requestDuration"`
WaitResponseDuration time.Duration `json:"waitResponseDuration,omitempty" yaml:"waitResponseDuration" xml:"waitResponseDuration"`
ResponseDuration time.Duration `json:"responseDuration,omitempty" yaml:"responseDuration" xml:"responseDuration"`
TotalDuration time.Duration `json:"totalDuration,omitempty" yaml:"totalDuration" xml:"totalDuration"`
// contains filtered or unexported fields
}