package httpclent import ( "context" "io" "net/http" "net/url" "sync" "time" ) const ( SchemeHttp Scheme = "http" SchemeHttps Scheme = "https" SchemeFtp Scheme = "ftp" SchemeWs Scheme = "ws" SchemeWss Scheme = "wss" ) /** header or const */ const ( _ServerName = "server-name" ) // http 协议方式 type Scheme string type HttpMethod string func (s Scheme) NewUrl(host string) string { return string(s) + host } const ( MethodGet HttpMethod = "GET" MethodHead HttpMethod = "HEAD" MethodPost HttpMethod = "POST" MethodPut HttpMethod = "PUT" MethodPatch HttpMethod = "PATCH" // RFC 5789 MethodDelete HttpMethod = "DELETE" MethodConnect HttpMethod = "CONNECT" MethodOptions HttpMethod = "OPTIONS" MethodTrace HttpMethod = "TRACE" ) // 请求参数 type RequestParams map[string]interface{} // 创建http request type NewHttpRequestFunc func() (*http.Request, error) // 设置请求header,在请求之前设置 type HandlerRequestHeader func(ctx context.Context, header http.Header) // 添加request-cookie,requestCookie是请求中已经带有的Cookie,不能返回requestCookie type AddRequestCookies func(ctx context.Context, requestCookie []*http.Cookie) []*http.Cookie // 设置请求体,在请求之前设置,oldReq传入的req,newReq传出的 type HandlerRequestParams func(ctx context.Context, oldReq interface{}) (newReq interface{}) // 获取server_name 对应的uri type ServerHostUrl func(ctx context.Context, serverName string) (string, error) type HandlerResponse func(ctx context.Context, response *http.Response) error type HandlerRequestUrl func(ctx context.Context, _url *url.URL) error type EncodeRequestBody func(ctx context.Context, params interface{}) (io.Reader, error) var ( // 降低内存开销,切记使用pool记得用指针类型,不然会有额外的内存开销! optionsPool = sync.Pool{ New: func() interface{} { return new(Options) }, } ) type Option func(*Options) type Options struct { // Client客户端配置 TimeOut time.Duration // 超时时间,默认1s RetryMaxNum int // 重试次数,默认重试2次,如果值设置为0则不重试 RetryIdleTime time.Duration // 再次重试的等待时间,默认1ms HandlerRequestHeader HandlerRequestHeader // 处理请求头,默认添加 content-type:application/json // Deprecated HandlerRequestParams HandlerRequestParams // 处理请求参数,默认添加 params,不推荐使用,推荐直接使用 EncodeRequestBody ServerHostUrl ServerHostUrl // 获取请求IP:PORT,可以为空 Scheme Scheme // http协议方式,默认http AddRequestCookies AddRequestCookies // 处理http-request HttpMethod HttpMethod // Http请求方式,默认POST HandlerRequestUrl HandlerRequestUrl // 处理请求url,可以添加url的请求参数 EncodeRequestBody EncodeRequestBody // 解析请求参数,默认是Json HandlerResponse HandlerResponse // 处理响应 } // 加载OP-CONFIG,使用 sync.Pool 可以降低内存开销!记得用完调用FreeOp func LoadDefaultOp(option ...Option) *Options { op := optionsPool.Get().(*Options) // init op.TimeOut = 0 op.RetryMaxNum = 0 op.RetryIdleTime = 0 op.HandlerRequestHeader = nil op.HandlerRequestParams = nil op.ServerHostUrl = nil op.Scheme = "" op.AddRequestCookies = nil op.HttpMethod = "" op.HandlerRequestUrl = nil op.EncodeRequestBody = nil op.HandlerResponse = nil for _, elem := range option { if elem != nil { elem(op) } } return op } func FreeOp(options *Options) { if options != nil { optionsPool.Put(options) } }