Documentation ¶
Index ¶
- Variables
- func Get(url string) (resp *http.Response, err error)
- func Head(url string) (resp *http.Response, err error)
- func Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
- func PostForm(url string, data url.Values) (resp *http.Response, err error)
- type BodySizeOption
- type CacheOption
- type CacheTTLFunc
- type Cacher
- type Client
- func (c *Client) Do(req *http.Request) (*http.Response, error)
- func (c *Client) Get(url string) (resp *http.Response, err error)
- func (c *Client) Head(url string) (resp *http.Response, err error)
- func (c *Client) Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
- func (c *Client) PostForm(url string, data url.Values) (resp *http.Response, err error)
- type Doer
- type FileCache
- type HTTPHeader
- type HTTPRequestResponse
- type HystrixContructor
- type HystrixOption
- type LoggerEntry
- type LoggerFunc
- type LoggerOption
- type MemoryCache
- type Option
- func WithCacheOption(option CacheOption) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHystrixOption(option HystrixOption) Option
- func WithLoggerOption(option LoggerOption) Option
- func WithMaxBodySize(n uint64) Option
- func WithMaxRetry(n uint64) Option
- func WithRateLimitOption(option RateLimitOption) Option
- func WithRequestTimeout(timeout time.Duration) Option
- func WithRetryBackOff(b backoff.BackOff) Option
- func WithShouldRetryFunc(fn ShouldRetryFunc) Option
- func WithTraceOption(option TraceOption) Option
- type RateLimitConstructor
- type RateLimitFunc
- type RateLimitOption
- type RedisCache
- type RequestEntry
- type RequestEntryEncoderDecoder
- type RequestHandler
- func BodySizeHandler(option BodySizeOption) RequestHandler
- func CacheHandler(option CacheOption) RequestHandler
- func ChainRequestHandlers(handlers ...RequestHandler) RequestHandler
- func HystrixHandler(option HystrixOption) RequestHandler
- func LoggerHandler(option LoggerOption) RequestHandler
- func RateLimitHandler(option RateLimitOption) RequestHandler
- func RetryHandler(option RetryOption) RequestHandler
- func TraceHandler(option TraceOption) RequestHandler
- type RequestHandlerFunc
- type RequestHashFunc
- type RetryOption
- type ShouldCacheFunc
- type ShouldRetryFunc
- type TraceComponentNameFunc
- type TraceOption
Constants ¶
This section is empty.
Variables ¶
var DefaultClient = NewClient()
DefaultClient is the default implementation of the client, the same as the official http package.
var ErrCacheKeyNotFound = errors.New("cache key not found")
ErrCacheKeyNotFound is a cached key does not exist error.
Functions ¶
Types ¶
type BodySizeOption ¶
type BodySizeOption struct {
MaxBodySize uint64
}
BodySizeOption is used to set the maximum size of the server response data.
func NewBodySizeOption ¶
func NewBodySizeOption(maxBodySize uint64) BodySizeOption
NewBodySizeOption is used to create an option configuration, and the parameter maxBodySize sets the maximum number of bytes of data returned by the server. In detail, the restriction is implemented through the Content-Length field of the HTTP response header returned by the server. The limit can only limit honest servers.
type CacheOption ¶
type CacheOption struct { ShouldCacheFunc ShouldCacheFunc RequestHashFunc RequestHashFunc CacheTTLFunc CacheTTLFunc Cacher Cacher EncoderDecoder RequestEntryEncoderDecoder }
CacheOption is the options structure that sets the cache.
func NewCacheOption ¶
func NewCacheOption(cacher Cacher) CacheOption
NewCacheOption creates a new cache option and passes in a cache method. The cache function will save the content of the response, such as saving to memory, file, Redis, etc. The next time you initiate the same request, you don't need to actually execute the request, but extract it from the cache.
func NewMemoryCacheOption ¶
func NewMemoryCacheOption() CacheOption
NewMemoryCacheOption creates a new cached option and caches the request and response data in memory.
type CacheTTLFunc ¶
CacheTTLFunc can configure different cache times for different requests.
var DefaultCacheTTLFunc CacheTTLFunc = func(*http.Request, *http.Response, error) time.Duration { return 5 * time.Minute }
DefaultCacheTTLFunc is the default implemented function that sets the cache time based on the request context. By default, it caches all requests that need to be cached for 5 minutes.
type Cacher ¶
type Cacher interface { Get(key []byte) ([]byte, error) Set(key, value []byte, ttl time.Duration) error }
Cacher is the cached interface and requires Get and Set methods.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP request client and is fully compatible with the net.http package. And provides functions such as retry, rate limit, circuit breaker, cache, log, and trace. This package can be used as a basic toolkit for a microservice framework with HTTP requests as a carrier, or as a more secure library to limit the size of concurrent requests and downloaded data.
func NewClient ¶
NewClient creates a new HTTP request client. If no setting options are passed in, then it behaves exactly the same as the official package. You can use the WithXXX series of methods to configure options. It provides advanced functions such as retry, rate limit, circuit breaker, cache, log, and trace.
type Doer ¶
Doer is the interface for initiating requests, it needs to implement the Do method, and http.Client has implemented this interface.
type FileCache ¶
FileCache saves data to the file system and implements the Cacher interface.
func NewFileCache ¶
NewFileCache creates an instance of the file system cache, and save the storage data in the rootDir directory in the form of files. Note that files are not removed periodically, only when they are accessed and found to be out of date.
type HTTPHeader ¶
HTTPHeader holds HTTP request and response headers.
type HTTPRequestResponse ¶
type HTTPRequestResponse struct { Method string URL string RequestHeader map[string]string RequestBody []byte Status string StatusCode int Proto string ProtoMajor int ProtoMinor int ResponseHeader map[string]string ResponseBody []byte Error []byte }
HTTPRequestResponse is an intermediate temporary structure for the request context.
type HystrixContructor ¶
type HystrixContructor func(req *http.Request, option HystrixOption) *circuit.Circuit
HystrixContructor defines a function pointer to an instance of the circuit breaker.
type HystrixOption ¶
type HystrixOption struct { CircuitManager *circuit.Manager HystrixContructor HystrixContructor }
HystrixOption is an option configuration for the circuit breaker.
func NewHystrixOption ¶
func NewHystrixOption() HystrixOption
NewHystrixOption creates an option configuration for a circuit breaker. Circuit breakers use the Hystrix Pattern, which is a complex concept and requires a lot of effort to understand. The circuit breaker is divided into two states: closed circuit and open circuit. It is closed at first, but if there are many request failures, it will become open. In the open-circuit state, no more requests will be initiated, and after a period of time, the request will be passed to test whether the link is normal. If it is normal, it will become a closed state, and the request will be unblocked. The default settings are to request 20 times, and if half of them fail, it becomes an open-circuit state. Then wait for 5 seconds, then retries 1 time, and if successful, it changes back to the closed-circuit state.
type LoggerEntry ¶
type LoggerEntry struct { Method string URL string RequestHeader http.Header RequestBody []byte ResponseHeader http.Header ResponseBody []byte StatusCode int ExecuteTime time.Duration StartTime time.Time }
LoggerEntry is the entry that records the request context.
type LoggerFunc ¶
type LoggerFunc func(req *http.Request, e LoggerEntry, option LoggerOption)
LoggerFunc defines a function for logging.
type LoggerOption ¶
type LoggerOption struct { LogMessage string LogRequestHeader bool LogRequestBody bool LogResponseHeader bool LogResponseBody bool Logger *logrus.Entry LoggerFunc LoggerFunc }
LoggerOption is an option configuration for logging.
func NewLoggerOption ¶
func NewLoggerOption() LoggerOption
NewLoggerOption creates a log option configuration. By default it will record the request body and the response body, which will have a certain performance loss, you can choose to turn it off.
type MemoryCache ¶
type MemoryCache struct {
// contains filtered or unexported fields
}
MemoryCache stores data in memory and implements the Cacher interface.
func NewMemoryCache ¶
func NewMemoryCache() MemoryCache
NewMemoryCache creates an in-memory cache instance. Note that the data it holds is limited by the operating system's memory resources.
type Option ¶
type Option func(c *Client)
Option defines the signature of the options configuration family of methods.
func WithCacheOption ¶
func WithCacheOption(option CacheOption) Option
WithCacheOption sets the cache configuration.
func WithHTTPClient ¶
WithHTTPClient sets options for a custom http.Client instance.
func WithHystrixOption ¶
func WithHystrixOption(option HystrixOption) Option
WithHystrixOption sets the configuration of the circuit breaker.
func WithLoggerOption ¶
func WithLoggerOption(option LoggerOption) Option
WithLoggerOption sets whether to enable the logging function to record the context information of the request.
func WithMaxBodySize ¶
WithMaxBodySize sets the maximum limit on the size of data returned by the server.
func WithMaxRetry ¶
WithMaxRetry sets the maximum number of retries. When n=0, it means that no retry operation is performed, instead of retrying until success.
func WithRateLimitOption ¶
func WithRateLimitOption(option RateLimitOption) Option
WithRateLimitOption sets the rate-limiting configuration and limits the maximum number of requests per second.
func WithRequestTimeout ¶
WithRequestTimeout sets the timeout for the entire request.
func WithRetryBackOff ¶
func WithRetryBackOff(b backoff.BackOff) Option
WithRetryBackOff sets the retry policy. You can choose a constant retry interval, or use an exponential back off algorithm.
func WithShouldRetryFunc ¶
func WithShouldRetryFunc(fn ShouldRetryFunc) Option
WithShouldRetryFunc sets the function that determines whether a retry is required.
func WithTraceOption ¶
func WithTraceOption(option TraceOption) Option
WithTraceOption sets the configuration for distributed call chain tracing.
type RateLimitConstructor ¶
RateLimitConstructor defines the constructor of a rate limiter.
type RateLimitFunc ¶
type RateLimitFunc func(req *http.Request, option RateLimitOption) error
RateLimitFunc enforces the rate limit.
var RateLimitAllRequestsFunc RateLimitFunc = func(req *http.Request, option RateLimitOption) error { key := "__all__" val, _ := option.RateLimits.LoadOrStore(key, option.RateLimitConstructor()) rl := val.(ratelimit.Limiter) _ = rl.Take() return nil }
RateLimitAllRequestsFunc enforces a rate limit, each request is included in the rate limit, and it does not distinguish the domain name of the request.
type RateLimitOption ¶
type RateLimitOption struct { Rate int RateLimitConstructor RateLimitConstructor RateLimits *sync.Map RateLimitFunc RateLimitFunc }
RateLimitOption defines a rate limit option configuration.
func NewRateLimitOption ¶
func NewRateLimitOption(rate int) RateLimitOption
NewRateLimitOption creates a rate limit option configuration. The parameter rate defines the maximum number of requests per second. If it exceeds maximum times, the excess requests will wait until the next second to execute. The requested address needs to be specially explained, and the parameters after the link question mark will be omitted. Different requested addresses have different capacity of maximum times per second. Of course, you can also customize the algorithm and stipulate that different domain names use different capacity limits.
type RedisCache ¶
type RedisCache struct { Prefix string // contains filtered or unexported fields }
RedisCache stores data in redis server and implements the Cacher interface.
func NewRedisCache ¶
func NewRedisCache(c *redis.Client) RedisCache
NewRedisCache creates an instance of the redis server cache, The default key has no prefix, of course you can set one yourself.
type RequestEntry ¶
RequestEntry is a structure that stores the request context.
type RequestEntryEncoderDecoder ¶
type RequestEntryEncoderDecoder interface { Encode(entry RequestEntry) ([]byte, error) Decode([]byte) (RequestEntry, error) }
RequestEntryEncoderDecoder is an interface to serialize and deserialize the request context.
type RequestHandler ¶
type RequestHandler func(req *http.Request, handlerFunc RequestHandlerFunc) (resp *http.Response, err error)
RequestHandler defines interceptors for requests.
func BodySizeHandler ¶
func BodySizeHandler(option BodySizeOption) RequestHandler
BodySizeHandler is the interceptor that the server returns the data size limit.
func CacheHandler ¶
func CacheHandler(option CacheOption) RequestHandler
CacheHandler is a cache interceptor that caches request content and server-side response content.
func ChainRequestHandlers ¶
func ChainRequestHandlers(handlers ...RequestHandler) RequestHandler
ChainRequestHandlers merges multiple interceptors sequentially into a single interceptor.
func HystrixHandler ¶
func HystrixHandler(option HystrixOption) RequestHandler
HystrixHandler implements a circuit breaker interceptor.
func LoggerHandler ¶
func LoggerHandler(option LoggerOption) RequestHandler
LoggerHandler implements a logging interceptor that logs the request context.
func RateLimitHandler ¶
func RateLimitHandler(option RateLimitOption) RequestHandler
RateLimitHandler creates a rate-limiting interceptor that limits the maximum number of requests per second.
func RetryHandler ¶
func RetryHandler(option RetryOption) RequestHandler
RetryHandler creates a retry interceptor that can set the maximum number of retries, and the time interval between each retry.
func TraceHandler ¶
func TraceHandler(option TraceOption) RequestHandler
TraceHandler creates a distributed tracing interceptor that can record and display call chain information through opentracing.
type RequestHandlerFunc ¶
RequestHandlerFunc defines the handler function for request interception.
type RequestHashFunc ¶
RequestHashFunc generates a hash value based on the context of the request as a cache key.
var DefaultRequestHashFunc RequestHashFunc = func(req *http.Request, resp *http.Response, err error) []byte { ok := req != nil && req.URL != nil && req.Method == http.MethodGet if !ok { return nil } bv := []byte(req.URL.String()) hasher := sha1.New() hasher.Write(bv) sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) return []byte(sha) }
DefaultRequestHashFunc is a function implemented by default to generate different hash values as cache keys according to different requests.
type RetryOption ¶
type RetryOption struct { ShouldRetryFunc ShouldRetryFunc MaxRetry uint64 RetryBackOff backoff.BackOff }
RetryOption defines a retry option configuration.
func NewRetryOption ¶
func NewRetryOption(maxRetry uint64, retryBackOff backoff.BackOff) RetryOption
NewRetryOption creates a retry options configuration. Set the request to repeat up to maxRetry times when it fails. You can set a constant retry interval, or you can use the Exponential backoff algorithm. Exponential backoff is an algorithm that uses feedback to multiplicatively decrease the rate of some process, in order to gradually find an acceptable rate. The default algorithm for judging retry is that the HTTP status code is greater than or equal to 500 before retrying.
type ShouldCacheFunc ¶
ShouldCacheFunc is a function pointer to determine whether a request needs to be cached.
var DefaultShouldCacheFunc ShouldCacheFunc = func(req *http.Request, resp *http.Response, err error) bool { ok := req != nil && req.URL != nil && req.Method == http.MethodGet && resp != nil && resp.StatusCode == http.StatusOK && err == nil return ok }
DefaultShouldCacheFunc is a function implemented by default to determine whether a request needs to be cached. By default, only successful requests with HTTP method GET and status code 200 will be cached for 5 minutes. The same complete request link will be treated as the same request and may be cached.
type ShouldRetryFunc ¶
ShouldRetryFunc defines a function that determines whether a retry is required.
type TraceComponentNameFunc ¶
TraceComponentNameFunc defines a function that gets the name of the tracking component by request.
var DefaultTraceComponentNameFunc TraceComponentNameFunc = func(req *http.Request) string { if req == nil || req.URL == nil { return "HTTP NULL" } return fmt.Sprintf("HTTP %s %s", req.Method, req.URL.Path) }
DefaultTraceComponentNameFunc is a default function that defines the name of a tracked component by request.
type TraceOption ¶
type TraceOption struct { Enabled bool Tracer opentracing.Tracer ComponentName string ComponentNameFunc TraceComponentNameFunc ClientConnectionTrace bool }
TraceOption defines an option configuration for distributed tracing.
func NewTraceOption ¶
func NewTraceOption() TraceOption
NewTraceOption creates a new option configuration for distributed tracing. Distributed tracing integrates with the Jaeger project, you can visit jaegertracing.io for more information.