package invoke import ( "git.sxidc.com/service-supports/dapr_api/utils" "github.com/go-resty/resty/v2" "net/url" "time" ) var ( contentTypeJSONHeader = map[string]string{"ContentType": "application/json"} ) type API struct { client *resty.Client baseUrl string } func NewAPI(baseUrl string, timeout time.Duration) *API { return &API{ client: resty.New().SetTimeout(timeout), baseUrl: baseUrl, } } func DestroyAPI(api *API) { if api == nil { return } api.baseUrl = "" api.client = nil } func (api *API) PostJSON(methodName string, data []byte) ([]byte, error) { return api.Post(methodName, contentTypeJSONHeader, data) } func (api *API) PutJSON(methodName string, data []byte) ([]byte, error) { return api.Put(methodName, contentTypeJSONHeader, data) } func (api *API) PostWithoutHeaders(methodName string, data []byte) ([]byte, error) { return api.Post(methodName, nil, data) } func (api *API) PutWithoutHeaders(methodName string, data []byte) ([]byte, error) { return api.Put(methodName, nil, data) } func (api *API) DeleteWithoutHeaders(methodName string) ([]byte, error) { return api.Delete(methodName, nil) } func (api *API) GetWithoutHeaders(methodName string) ([]byte, error) { return api.Get(methodName, nil) } func (api *API) Post(methodName string, headers map[string]string, data []byte) ([]byte, error) { invokeUrl, err := url.JoinPath(api.baseUrl, methodName) if err != nil { return nil, err } resp, err := api.client.R(). SetHeaders(headers). SetBody(data). Post(invokeUrl) if err != nil { return nil, err } if resp.IsError() { return nil, utils.ResponseStatusError(invokeUrl, resp) } return resp.Body(), nil } func (api *API) Delete(methodName string, headers map[string]string) ([]byte, error) { invokeUrl, err := url.JoinPath(api.baseUrl, methodName) if err != nil { return nil, err } resp, err := api.client.R(). SetHeaders(headers). Delete(invokeUrl) if err != nil { return nil, err } if resp.IsError() { return nil, utils.ResponseStatusError(invokeUrl, resp) } return resp.Body(), nil } func (api *API) Put(methodName string, headers map[string]string, data []byte) ([]byte, error) { invokeUrl, err := url.JoinPath(api.baseUrl, methodName) if err != nil { return nil, err } resp, err := api.client.R(). SetHeaders(headers). SetBody(data). Put(invokeUrl) if err != nil { return nil, err } if resp.IsError() { return nil, utils.ResponseStatusError(invokeUrl, resp) } return resp.Body(), nil } func (api *API) Get(methodName string, headers map[string]string) ([]byte, error) { invokeUrl, err := url.JoinPath(api.baseUrl, methodName) if err != nil { return nil, err } resp, err := api.client.R(). SetHeaders(headers). Get(invokeUrl) if err != nil { return nil, err } if resp.IsError() { return nil, utils.ResponseStatusError(invokeUrl, resp) } return resp.Body(), nil }