You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package http
|
|
|
|
import (
|
|
"errors"
|
|
jsoniter "github.com/json-iterator/go"
|
|
"github.com/spf13/viper"
|
|
"go.uber.org/zap"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
json2 = jsoniter.ConfigCompatibleWithStandardLibrary
|
|
jsonHeader = http.Header{"content-type": []string{"application/json"}}
|
|
logger *zap.Logger
|
|
)
|
|
|
|
type Client struct {
|
|
url string
|
|
client *http.Client
|
|
}
|
|
|
|
func NewClient() *Client {
|
|
url := viper.GetString("application.sms.url")
|
|
return &Client{
|
|
url: strings.TrimSuffix(url, "/"),
|
|
client: &http.Client{},
|
|
}
|
|
}
|
|
|
|
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) {
|
|
req, err := http.NewRequest(method, c.url+path, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for k, v := range header {
|
|
req.Header[k] = v
|
|
}
|
|
|
|
return c.client.Do(req)
|
|
}
|
|
|
|
//goland:noinspection ALL
|
|
func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) {
|
|
resp, err := c.doRequest(method, path, header, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
data, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
switch resp.StatusCode {
|
|
case 403:
|
|
return nil, errors.New("403 Forbidden")
|
|
case 404:
|
|
return nil, errors.New("404 Not Found")
|
|
}
|
|
|
|
if resp.StatusCode/100 != 2 {
|
|
errMap := make(map[string]interface{})
|
|
if err = json2.Unmarshal(data, &errMap); err != nil {
|
|
return nil, err
|
|
}
|
|
return nil, errors.New(errMap["message"].(string))
|
|
}
|
|
logger.Info("response:" + string(data))
|
|
return data, nil
|
|
}
|
|
|
|
func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error {
|
|
data, err := c.getResponse(method, path, header, body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return json2.Unmarshal(data, obj)
|
|
}
|