package httpclent import ( "bytes" "context" "encoding/json" "errors" "io" "io/ioutil" "net/url" "time" "git.shuncheng.lu/bigthing/gocommon/pkg/net/auth" "git.shuncheng.lu/bigthing/gocommon/pkg/net/nacos" "net/http" ) var ( NacosServerHostOption Option = func(options *Options) { options.ServerHostUrl = NacosServerHost } QconfServerHostOption Option = func(options *Options) { options.ServerHostUrl = DefaultServerHost } DomainServerHostOption Option = func(options *Options) { options.ServerHostUrl = DomainServerHost } ) var ( SetUrlRequestParams = func(values url.Values) HandlerRequestUrl { return func(ctx context.Context, _url *url.URL) error { _url.RawQuery = values.Encode() return nil } } ) var ( DefaultTimeOut2sOp = func(op *Options) { op.TimeOut = 2 * time.Second } DefaultTimeOut3sOp = func(op *Options) { op.TimeOut = 3 * time.Second } DefaultTimeOut4sOp = func(op *Options) { op.TimeOut = 4 * time.Second } DefaultTimeOut5sOp = func(op *Options) { op.TimeOut = 5 * time.Second } // 关闭重试 CloseRetry = func(op *Options) { op.RetryMaxNum = -1 } // 默认处理 DefaultHandlerRequestParams HandlerRequestParams = func(ctx context.Context, oldReq interface{}) (newReq interface{}) { return RequestParams{"params": oldReq} } // 默认处理 DefaultHandlerRequestHandler HandlerRequestHeader = func(ctx context.Context, header http.Header) { header.Add("Content-Type", "application/json") header.Add("Service-Token", auth.GenerateToken(getServerName(ctx))) } DefaultServerHost ServerHostUrl = func(ctx context.Context, serverName string) (s string, e error) { return GetServerUrl(serverName) } NacosServerHost ServerHostUrl = func(ctx context.Context, serverName string) (s string, e error) { return nacos.GetHost(serverName) } DomainServerHost ServerHostUrl = func(ctx context.Context, serverName string) (s string, e error) { return nacos.GetDomainHost(serverName) } DefaultEncodeRequestBody EncodeRequestBody = func(ctx context.Context, params interface{}) (reader io.Reader, e error) { if params == nil { return nil, nil } buf := bytes.Buffer{} if err := json.NewEncoder(&buf).Encode(params); err != nil { return nil, fmtError("[DefaultEncodeRequestBody] err,err=%+v,req=%+v", err, params) } return ioutil.NopCloser(&buf), nil } ) var ( // error validateNilError = errors.New("the result can not be null") validateTypeError = errors.New("the result must be a pointer type") ) const ( defaultRetryNum = 2 //默认重试2次,带上第一次请求,一共请求3次 defaultMethod = MethodPost //默认Post请求 defaultScheme = SchemeHttp defaultTimeOut1s = 1 * time.Second //默认超时时间1s defaultRetryIdleTime = 1 * time.Millisecond // 默认空闲时间是1ms )