update
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
Timeout time.Duration
|
||||
MaxRetry int
|
||||
}
|
||||
|
||||
func NewRequest() *Request {
|
||||
return &Request{
|
||||
Timeout: time.Second * 2,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Request) SetTimeout(t time.Duration) {
|
||||
r.Timeout = t
|
||||
}
|
||||
|
||||
func (r *Request) SetMaxRetry(retry int) {
|
||||
r.MaxRetry = retry
|
||||
}
|
||||
|
||||
func (r *Request) Post(api string, data []byte) (string, error) {
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: r.Timeout,
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", api, bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
return "", errors.New("Error creating request:" + err.Error())
|
||||
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
retry := 0
|
||||
reqDo:
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
if r.MaxRetry > 0 {
|
||||
if retry < r.MaxRetry {
|
||||
retry = retry + 1
|
||||
log.Printf("请求api第[%d], 最大重试次数[%d]", retry, r.MaxRetry)
|
||||
goto reqDo
|
||||
}
|
||||
}
|
||||
return "", errors.New("Error sending request:" + err.Error())
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return "", fmt.Errorf("Error StatusCode: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", errors.New("Error read body: " + err.Error())
|
||||
}
|
||||
|
||||
return string(body), nil
|
||||
}
|
||||
Reference in New Issue
Block a user