Documentation
¶
Overview ¶
Package gopkg/httpx is a componentized http plugin.
It provides an easy way to configre and manage http client.
Based on https://resty.dev/
Example ¶
package main
import (
"context"
"github.com/wwwangxc/gopkg/httpx"
)
func main() {
// Load config (optional)
// gopkg/httpx will automatically read configuration
// files (./app.yaml) when package loaded
httpx.LoadConfig("./custom_config.yaml")
// Create HTTP/HTTPS client with config
cli := httpx.NewClientProxy("name")
// Send HTTP/HTTPX GET request
var rsp map[string]any
_ = cli.Get(context.Background(), "https://httpbin.org/anything", &rsp)
}
Output:
Index ¶
- Variables
- func LoadConfig(path string) error
- type AllowMethodDeletePayloadGetter
- type AllowMethodGetPayloadGetter
- type AllowResponseBodyUnlimitedReadsGetter
- type BasicAuthGetter
- type BearerTokenAuthGetter
- type BodyGetter
- type ClientOption
- type ClientProxy
- type CookiesGetter
- type DebugGetter
- type ExpectResponseContentTypeGetter
- type ForceResponseContentTypeGetter
- type FormParamsGetter
- type HeaderGetter
- type MethodGetter
- type PathParamsGetter
- type QueryParamsGetter
- type QueryStringGetter
- type RequestChecker
- type RequestOption
- type RequestProtocol
- type RetryGetter
- type RetryHooksGetter
- type RetryWaitGetter
- type TimeoutGetter
- type TraceGetter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var C = (*clientOption)(nil)
C is the client proxy option provider
var R = (*requestOption)(nil)
R is the request option provider
Functions ¶
Types ¶
type AllowMethodDeletePayloadGetter ¶
type AllowMethodDeletePayloadGetter interface{ AllowMethodDeletePayload() }
AllowMethodDeletePayloadGetter return nothing
Implement this interface will allows the DELETE method with payload on the Resty client.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) AllowMethodDeletePayloadGetter() {}
type AllowMethodGetPayloadGetter ¶
type AllowMethodGetPayloadGetter interface{ AllowMethodGetPayload() }
AllowMethodGetPayloadGetter return nothing
Implement this interface will allows the GET method with payload on the Resty client.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) AllowMethodGetPayloadGetter() {}
type AllowResponseBodyUnlimitedReadsGetter ¶
type AllowResponseBodyUnlimitedReadsGetter interface{ AllowResponseBodyUnlimitedReads() }
AllowResponseBodyUnlimitedReadsGetter return nothing
Implement this interface for enable the response body in memory that provides an ability to do unlimited reads.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) AllowResponseBodyUnlimitedReadsGetter() {}
Unlimited reads are possible in a few scenarios, even without enabling it.
- When debug mode is enabled
NOTE: Use with care
- Turning on this feature keeps the response body in memory, which might cause additional memory usage.
type BasicAuthGetter ¶
type BasicAuthGetter interface {
BasicAuth() (username, password string)
}
BasicAuth returns username & password in basic authentication
Implement this interface to automatically set the Basic Authentication header in the current HTTP request.
Header Format:
Authorization: Basic <base64-encoded-value>
Usage Example:
type MyRequest struct{}
func (s *MyRequest) BasicAuth() (username, password string) {
return "username", "password"
}
type BearerTokenAuthGetter ¶
type BearerTokenAuthGetter interface{ BearerTokenAuth() string }
BearerTokenAuthGetter returns authentication token
Implement this interface to automatically set the Bearer Authentication header in the current HTTP request.
Header Format:
Authorization: Bearer <token>
Usage Example:
type MyRequest struct{}
func (s *MyRequest) BearerTokenAuth() string {
return "token"
}
type BodyGetter ¶
type BodyGetter interface{ Body() any }
BodyGetter returns the body in the current request
Implement this interface to automatically set the body in the current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Body() any {
// support string
return `{"params": "value"}`
// support []byte
return []byte("This is my raw request")
// support map
return map[string]any {
"params": "value",
}
// support struct
return Request {
Params: "value",
}
}
type ClientProxy ¶
type ClientProxy interface {
// Do http request by protocol
Do(ctx context.Context, req RequestProtocol, dest any) error
// Get will do http GET request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Get(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Head will do http HEAD request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Head(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Post will do http POST request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Post(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Put will do http PUT request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Put(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Delete will do http DELETE request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Delete(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Options will do http OPTIONS request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Options(ctx context.Context, url string, dest any, opts ...RequestOption) error
// Patch will do http PATCH request
//
// URL format such as:
// Normal: http://127.0.0.1:8080/v1/users/details
// With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
Patch(ctx context.Context, url string, dest any, opts ...RequestOption) error
}
ClientProxy http client proxy
func NewClientProxy ¶
func NewClientProxy(name string, opt ...ClientOption) ClientProxy
NewClientProxy new http client proxy
Example ¶
package main
import (
"net/http"
"time"
"resty.dev/v3"
"github.com/wwwangxc/gopkg/httpx"
)
func main() {
// Create HTTP/HTTPS client proxy with config
_ = httpx.NewClientProxy("name")
// Create HTTP/HTTPX client proxy with options
_ = httpx.NewClientProxy("name",
httpx.C.WithHost("httpbin1.org", "httpbin2.org"),
httpx.C.WithTimeout(3*time.Second),
httpx.C.WithHeader(map[string]string{}),
httpx.C.WithTransport(&http.Transport{}),
httpx.C.WithRequestMiddlewares([]resty.RequestMiddleware{}...),
httpx.C.WithResponseMiddlewares([]resty.ResponseMiddleware{}...),
httpx.C.OnSuccess(func(c *resty.Client, r *resty.Response) {}),
httpx.C.OnError(func(r *resty.Request, err error) {}),
httpx.C.OnInvalid(func(r *resty.Request, err error) {}),
httpx.C.OnPanic(func(r *resty.Request, err error) {}),
httpx.C.WithAllowMethodGetPayload(),
httpx.C.WithAllowMethodDeletePayload(),
httpx.C.WithTrace(),
httpx.C.WithDebug(),
)
}
Output:
type CookiesGetter ¶
CookieGetters returns the cookies of the current request
Implement this interface to automatically append the cookies in the current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Cookies() []*http.Cookie {
return []*http.Cookie{}
}
type DebugGetter ¶ added in v0.1.2
type DebugGetter interface{ Debug() }
DebugGetter return nothing
Implement this interface will enables the debug mode on the current request. It logs the details current request and response.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Debug() {}
type ExpectResponseContentTypeGetter ¶ added in v0.1.3
type ExpectResponseContentTypeGetter interface{ ExpectResponseContentType() string }
ExpectResponseContentTypeGetter returns fallback `Content-Type`
Implement this interface to automatically set the fallback `Content-Type` for automatic unmarshalling when the `Content-Type` response header is unavailable.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) ExpectResponseContentType() string {
return "application/json"
}
type ForceResponseContentTypeGetter ¶ added in v0.1.3
type ForceResponseContentTypeGetter interface{ ForceResponseContentType() string }
ForceResponseContentTypeGetter returns force `Content-Type`
Implement this interface to automatically set the force response `Content-Type` for the current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) ForceResponseContentType() string {
return "application/json"
}
type FormParamsGetter ¶
FormParamsGetter returns the form parameters in the current request
Implement this interface to automatically set the form parameters in the current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) FormParams() map[string]string {
return map[string]string{
"params_name": "666",
}
}
type HeaderGetter ¶
HeaderGetter returns the headers of the current request
Implement this interface to automatically set headers in the current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Header() map[string]string {
return map[string]string{
"Content-Type": "application/json;charset=UTF-8",
}
}
type MethodGetter ¶
type MethodGetter interface {
Method() string
}
MethodGetter returns http method
Implement this interface to set the method for current current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Method() { return http.MethodGet }
type PathParamsGetter ¶
PathParamsGetter returns the parameters in the current request path
Implement this interface to automatically set the parameters in the current HTTP request path.
URL Format:
Raw: /api/path/{params_name}
Cooked: /api/path/666
Usage Example:
type MyRequest struct{}
func (s *MyRequest) PathParams() map[string]string {
return map[string]string{
"params_name": "666",
}
}
type QueryParamsGetter ¶
QueryParamsGetter returns the query parameters in the current request
Implement this interface to automatically set the query parameters in the current HTTP request.
URL Format:
/api/path?params_1=value_1¶ms_2=value_2
Usage Example:
type MyRequest struct{}
func (s *MyRequest) QueryParams() map[string]string {
return map[string]string{
"params_1": "value_1",
"params_2": "value_2",
}
}
type QueryStringGetter ¶
type QueryStringGetter interface{ QueryString() string }
QueryStringGetter returns the query parameters string in the current request
Implement this interface to automatically set the query parameters string in the current HTTP request.
URL Format:
/api/path?params_1=value_1¶ms_2=value_2
Usage Example:
type MyRequest struct{}
func (s *MyRequest) QueryString() string {
return "params_1=value_1¶ms_2=value_2"
}
type RequestChecker ¶ added in v0.1.3
type RequestChecker interface{ Check() error }
RequestChecker check current request
Implement this interface to automatically check current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Check() error {
if s == nil {
return fmt.Error("invalid request")
}
return nil
}
type RequestProtocol ¶
RequestProtocol custom request protocol
By implementing the appropriate Getter interface for the request protocol, various options in the request can be set automatically.
Support checker && getter: - [RequestChecker] // check current request. - [MethodGetter] // sets the http method - [BasicAuthGetter] // sets the basic authentication header - [BearerTokenAuthGetter] // sets the auth token header - [CookiesGetter] // append cookies - [HeaderGetter] // set multiple header fields and their values - [PathParamsGetter] // set multiple URL path key-value pair - [QueryParamsGetter] // set multiple parameter - [QueryStringGetter] // set the query string - [FormParamsGetter] // set form parameters and their values - [BodyGetter] // set the request body - [TimeoutGetter] // set the request timeout - [RetryGetter] // set the retry times and conditions when the request failed - [RetryWaitGetter] // set the default wait time for sleep before retrying - [RetryHooksGetter] // set retry hooks - [AllowResponseBodyUnlimitedReadsGetter] // enable the response body in memory that provides an ability to do unlimited reads. - [AllowMethodGetPayloadGetter] // allows the GET method with payload. - [AllowMethodDeletePayloadGetter] // allows the DELETE method with payload. - [DebugGetter] // enable debug mode. - [TraceGetter] // enable trace for current request. - [ExpectResponseContentTypeGetter] // set fallback `Content-Type`. - [ForceResponseContentTypeGetter] // set force response `Content-Type`.
type RetryGetter ¶
type RetryGetter interface {
Retry() (retryTimes int, retryConds []resty.RetryConditionFunc)
}
RetryGetter returns retry strategy for current request
Implement this interface to automatically set the retry strategy for current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Retry() (retryTimes int, retryConds []resty.RetryConditionFunc) {
// retry 3 times when response code is http.StatusTooManyRequests or http.StatusBadRequest
return 3, []resty.RetryConditionFunc {
httpx.RetryWithStatusCodes(http.StatusTooManyRequests, http.StatusBadRequest),
}
// retry 3 times when returns error
return 3, nil
}
type RetryHooksGetter ¶
type RetryHooksGetter interface {
RetryHooks(ctx context.Context) []resty.RetryHookFunc
}
RetryHooksGetter returns retry hooks for current request
Implement this interface to automatically set the retry hooks for current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) RetryHooks(ctx context.Context) []resty.RetryHookFunc {
return []resty.RetryHookFunc{
func(r *resty.Response, err error) {
if err != nil {
fmt.Printf("retry once, because an error occurred, error:%+v", err)
return
}
if r != nil && r.Result() != nil {
fmt.Printf("retry once, response:%+v", r.Result())
}
},
}
}
type RetryWaitGetter ¶
RetryWaitGetter returns the wait time before retry sleep for current request
Implement this interface to automatically set the wait time before retry sleep for current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) RetryWait() time.Duration {
return time.Second
}
type TimeoutGetter ¶
TimeoutGetter returns timeout for current request
Implement this interface to automatically set the timeout for current HTTP request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Timeout() any {
return 3 * time.Second
}
type TraceGetter ¶ added in v0.1.2
type TraceGetter interface{ Trace() }
TraceGetter return nothing
Implement this interface will enables trace for the current request.
Usage Example:
type MyRequest struct{}
func (s *MyRequest) Trace() {}