github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/internal/openapi/v3/codegen/testdata/test/signclient.go (about) 1 package test 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "net/http" 8 9 "github.com/go-resty/resty/v2" 10 _querystring "github.com/google/go-querystring/query" 11 "github.com/opentracing-contrib/go-stdlib/nethttp" 12 "github.com/opentracing/opentracing-go" 13 "github.com/pkg/errors" 14 ddhttp "github.com/unionj-cloud/go-doudou/framework/http" 15 "github.com/unionj-cloud/go-doudou/framework/registry" 16 ) 17 18 type SignClient struct { 19 provider registry.IServiceProvider 20 client *resty.Client 21 rootPath string 22 } 23 24 func (receiver *SignClient) SetRootPath(rootPath string) { 25 receiver.rootPath = rootPath 26 } 27 28 func (receiver *SignClient) SetProvider(provider registry.IServiceProvider) { 29 receiver.provider = provider 30 } 31 32 func (receiver *SignClient) SetClient(client *resty.Client) { 33 receiver.client = client 34 } 35 36 // PostSignUp SignUp demonstrate how to define POST and Content-Type as application/x-www-form-urlencoded api 37 func (receiver *SignClient) PostSignUp(ctx context.Context, _headers map[string]string, 38 bodyParams SignUpReq) (ret SignUpResp, _resp *resty.Response, err error) { 39 var _err error 40 41 _req := receiver.client.R() 42 _req.SetContext(ctx) 43 if len(_headers) > 0 { 44 _req.SetHeaders(_headers) 45 } 46 _bodyParams, _ := _querystring.Values(bodyParams) 47 _req.SetFormDataFromValues(_bodyParams) 48 49 _resp, _err = _req.Post("/sign/up") 50 if _err != nil { 51 err = errors.Wrap(_err, "") 52 return 53 } 54 if _resp.IsError() { 55 err = errors.New(_resp.String()) 56 return 57 } 58 if _err = json.Unmarshal(_resp.Body(), &ret); _err != nil { 59 err = errors.Wrap(_err, "") 60 return 61 } 62 return 63 } 64 65 func NewSign(opts ...ddhttp.DdClientOption) *SignClient { 66 defaultProvider := ddhttp.NewServiceProvider("SIGN") 67 defaultClient := ddhttp.NewClient() 68 69 svcClient := &SignClient{ 70 provider: defaultProvider, 71 client: defaultClient, 72 } 73 74 for _, opt := range opts { 75 opt(svcClient) 76 } 77 78 svcClient.client.OnBeforeRequest(func(_ *resty.Client, request *resty.Request) error { 79 request.URL = svcClient.provider.SelectServer() + svcClient.rootPath + request.URL 80 return nil 81 }) 82 83 svcClient.client.SetPreRequestHook(func(_ *resty.Client, request *http.Request) error { 84 traceReq, _ := nethttp.TraceRequest(opentracing.GlobalTracer(), request, 85 nethttp.OperationName(fmt.Sprintf("HTTP %s: %s", request.Method, request.URL.Path))) 86 *request = *traceReq 87 return nil 88 }) 89 90 svcClient.client.OnAfterResponse(func(_ *resty.Client, response *resty.Response) error { 91 nethttp.TracerFromRequest(response.Request.RawRequest).Finish() 92 return nil 93 }) 94 95 return svcClient 96 }