123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- package http_client
- import (
- "das/application/ports"
- "encoding/json"
- "errors"
- "github.com/go-resty/resty/v2"
- )
- type Request struct {
- request *resty.Request
- }
- func (request *Request) SetHeaders(headers map[string]string) {
- request.request.SetHeaders(headers)
- }
- func (request *Request) SetQueryParams(queryParams map[string]string) {
- request.request.SetQueryParams(queryParams)
- }
- func (request *Request) SetPathParams(pathParams map[string]string) {
- request.request.SetPathParams(pathParams)
- }
- func (request *Request) Post(url string, body any, opts ...ports.RequestOption) (ports.HttpResponse, error) {
- for _, opt := range opts {
- opt(request)
- }
- restyRequest := request.request
- resp, err := restyRequest.SetBody(body).Post(url)
- if err != nil {
- return nil, err
- }
- if resp.IsError() {
- return nil, errors.New(resp.Status())
- }
- return &Response{response: resp}, nil
- }
- func (request *Request) Delete(url string, opts ...ports.RequestOption) (ports.HttpResponse, error) {
- for _, opt := range opts {
- opt(request)
- }
- restyRequest := request.request
- resp, err := restyRequest.Delete(url)
- if err != nil {
- return nil, err
- }
- if resp.IsError() {
- return nil, errors.New(resp.Status())
- }
- return &Response{response: resp}, nil
- }
- func (request *Request) Put(url string, body any, opts ...ports.RequestOption) (ports.HttpResponse, error) {
- for _, opt := range opts {
- opt(request)
- }
- restyRequest := request.request
- resp, err := restyRequest.SetBody(body).Put(url)
- if err != nil {
- return nil, err
- }
- if resp.IsError() {
- return nil, errors.New(resp.Status())
- }
- return &Response{response: resp}, nil
- }
- func (request *Request) Get(url string, opts ...ports.RequestOption) (ports.HttpResponse, error) {
- for _, opt := range opts {
- opt(request)
- }
- restyRequest := request.request
- resp, err := restyRequest.Get(url)
- if err != nil {
- return nil, err
- }
- if resp.IsError() {
- return nil, errors.New(resp.Status())
- }
- return &Response{response: resp}, nil
- }
- type Response struct {
- response *resty.Response
- }
- func (response *Response) Body() []byte {
- return response.response.Body()
- }
- func (response *Response) Json(resp any) error {
- body := response.response.Body()
- if body == nil || len(body) == 0 {
- return errors.New("响应体为空")
- }
- return json.Unmarshal(body, resp)
- }
|