58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package myHttp
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
)
|
|
|
|
func (t *Client) PostJson(request interface{}, response interface{}) error {
|
|
var buf bytes.Buffer
|
|
encoder := json.NewEncoder(&buf)
|
|
encoder.SetEscapeHTML(false)
|
|
if err := encoder.Encode(request); err != nil {
|
|
return err
|
|
}
|
|
|
|
// HTTP请求
|
|
req, err := http.NewRequest("POST", t.url.String(), &buf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
//添加请求头
|
|
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
|
if len(t.headers) > 0 {
|
|
for key, value := range t.headers {
|
|
req.Header.Set(key, value)
|
|
}
|
|
}
|
|
|
|
// 发送请求
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return errors.New("http.Status:" + resp.Status)
|
|
}
|
|
return json.NewDecoder(resp.Body).Decode(response)
|
|
}
|
|
|
|
func (t *Client) GetJson(response interface{}) error {
|
|
httpResp, err := http.Get(t.url.String())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer httpResp.Body.Close()
|
|
|
|
if httpResp.StatusCode != http.StatusOK {
|
|
return errors.New("http.Status:" + httpResp.Status)
|
|
}
|
|
return json.NewDecoder(httpResp.Body).Decode(response)
|
|
}
|