|
- package tool
-
- import (
- "bytes"
- "encoding/json"
- "github.com/go-resty/resty/v2"
- "io"
- "io/ioutil"
- "log"
- "net/http"
- "time"
- )
-
- const (
- GET = "GET"
- PUT = "PUT"
- POST = "POST"
- DELETE = "DELETE"
- )
- const (
- ContentType = "Content-Type"
- ApplicationJson = "application/json"
- )
-
- func GetACHttpRequest() *resty.Request {
-
- client := resty.New()
- request := client.R()
- return request
- }
-
- func HttpClient(method string, url string, payload io.Reader, token string) ([]byte, error) {
- request, err := http.NewRequest(method, url, payload)
- request.Header.Add("Content-Type", "application/json")
- request.Header.Add("User-Agent", "API Explorer")
- request.Header.Add("x-auth-token", token)
- client := &http.Client{}
- res, err := client.Do(request)
- if err != nil {
- log.Fatal(err)
- }
- defer res.Body.Close()
- body, err := io.ReadAll(res.Body)
- if err != nil {
- log.Fatal(err)
- }
-
- return body, err
- }
-
- // 发送POST请求
- // url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json
- // content:请求放回的内容
- func HttpPost(url string, data interface{}) (content string, err error) {
- jsonStr, _ := json.Marshal(data)
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
- req.Header.Add("content-type", "application/json")
- if err != nil {
- return
- }
- defer req.Body.Close()
-
- client := &http.Client{Timeout: 5 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return
- }
- defer resp.Body.Close()
-
- result, _ := ioutil.ReadAll(resp.Body)
- content = string(result)
- return
- }
|