package client import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "time" ) func NewClient() *http.Client { tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } return &http.Client{ Transport: tr, Timeout: 5 * time.Second, } } func Get(url string, headers map[string]string, params map[string]string) (res []byte, e error) { var ( client = NewClient() resp *http.Response ) req, _ := http.NewRequest(http.MethodGet, url, nil) for k, v := range headers { req.Header.Add(k, v) } q := req.URL.Query() for k, v := range params { q.Add(k, v) } req.URL.RawQuery = q.Encode() if resp, e = client.Do(req); e != nil { return } defer func(body io.ReadCloser) { _ = body.Close() }(resp.Body) if res, e = io.ReadAll(resp.Body); e != nil { return } if !success(resp.StatusCode) { e = errors.New(fmt.Sprintf("status code error: %s", resp.Status)) } return } func Post(url string, headers map[string]string, body map[string]any) (res []byte, e error) { var ( client = NewClient() resp *http.Response ) j, e := json.Marshal(body) if e != nil { return } req, _ := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(j)) for k, v := range headers { req.Header.Add(k, v) } //q := req.URL.Query() //for k, v := range params { // q.Add(k, v) //} //req.URL.RawQuery = q.Encode() if resp, e = client.Do(req); e != nil { return } defer func(body io.ReadCloser) { _ = body.Close() }(resp.Body) if res, e = io.ReadAll(resp.Body); e != nil { return } if !success(resp.StatusCode) { e = errors.New(fmt.Sprintf("status code error: %s", resp.Status)) } return } // func success(code int) bool { // return code >= 200 && code < 400 // }