发送 get 请求
func HttpGet(url string) (string, error) {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(content), nil
}
发送 post 请求
func HttpPost(url string, req interface{}) (string, error) {
var body []byte
body, err := json.Marshal(req)
if err != nil {
return "", err
}
client := &http.Client{Timeout: 10 * time.Second}
ct := "application/json"
resp, err := client.Post(url, ct, bytes.NewReader(body))
if err != nil {
return "", err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(content), nil
}
自定义的请求方式
func HttpDo(method string, url string, header map[string]string, req interface{}) (string, error) {
var body []byte
body, err := json.Marshal(req)
if err != nil {
return "", err
}
client := &http.Client{Timeout: 10 * time.Second}
nReq, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return "", err
}
for k, v := range header{
nReq.Header.Set(k, v)
}
resp, err := client.Do(nReq)
if err != nil {
return "", err
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", nil
}
return string(content), nil
}