package client import ( "git.sxidc.com/go-tools/utils/http_client" "time" ) const ( defaultTimeoutSec = 30 ) var instance *Client func InitInstance(timeout time.Duration) { if instance == nil { if timeout == 0 { timeout = defaultTimeoutSec * time.Second } instance = New(timeout) } } func GetInstance() *Client { if instance == nil { panic("还没有调用InitInstance") } return instance } type Client struct { client *http_client.Client timeout time.Duration } func New(timeout time.Duration) *Client { client := http_client.New() return &Client{ client: client, timeout: timeout, } } func (c *Client) post(token string, url string, request interface{}, result interface{}) error { req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout)) resp, err := req.Post(url, request, http_client.WithRequestHeaders(map[string]string{ "Content-Type": "application/json", "Authorization": token, })) if err != nil { return err } err = resp.Json(result) if err != nil { return err } return nil } func (c *Client) delete(token string, url string, queryMap map[string]string, result interface{}) error { req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout)) resp, err := req.Delete(url, http_client.WithRequestHeaders(map[string]string{ "Content-Type": "application/json", "Authorization": token, }), http_client.WithRequestQueryParams(queryMap)) if err != nil { return err } err = resp.Json(result) if err != nil { return err } return nil } func (c *Client) put(token string, url string, request interface{}, result interface{}) error { req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout)) resp, err := req.Put(url, request, http_client.WithRequestHeaders(map[string]string{ "Content-Type": "application/json", "Authorization": token, })) if err != nil { return err } err = resp.Json(result) if err != nil { return err } return nil } func (c *Client) get(token string, url string, queryMap map[string]string, result interface{}) error { req := c.client.NewRequest(http_client.WithNewRequestTimeout(c.timeout)) resp, err := req.Get(url, http_client.WithRequestHeaders(map[string]string{ "Content-Type": "application/json", "Authorization": token, }), http_client.WithRequestQueryParams(queryMap)) if err != nil { return err } err = resp.Json(result) if err != nil { return err } return nil }