2023-08-09 10:09:16 +00:00
|
|
|
package curl
|
|
|
|
|
|
|
|
import (
|
2023-10-13 09:44:02 +00:00
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2023-08-09 10:09:16 +00:00
|
|
|
"errors"
|
2023-08-09 11:34:11 +00:00
|
|
|
"io"
|
2023-08-09 10:09:16 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 接口请求
|
2023-08-09 11:34:11 +00:00
|
|
|
func ApiCall(url, method string, header map[string]string, body io.Reader, timeOut time.Duration) (rsp *http.Response, err error) {
|
2023-08-09 10:09:16 +00:00
|
|
|
method = strings.ToUpper(method)
|
|
|
|
if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" {
|
|
|
|
return nil, errors.New("invalid http method")
|
|
|
|
}
|
|
|
|
if url == "" {
|
|
|
|
return nil, errors.New("request url can`t be empty")
|
|
|
|
}
|
|
|
|
client := &http.Client{}
|
|
|
|
if timeOut <= 0 {
|
|
|
|
client.Timeout = time.Second * 15
|
|
|
|
} else {
|
|
|
|
client.Timeout = timeOut
|
|
|
|
}
|
2023-08-09 11:34:11 +00:00
|
|
|
requestHandle, err := http.NewRequest(method, url, body)
|
2023-08-09 10:09:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for k, v := range header {
|
|
|
|
requestHandle.Header.Set(k, v)
|
|
|
|
}
|
|
|
|
return client.Do(requestHandle)
|
|
|
|
}
|
2023-10-13 09:44:02 +00:00
|
|
|
|
|
|
|
// 请求(读取返回字节内容)
|
|
|
|
func ApiCall2(url, method string, header map[string]string, body io.Reader, timeOut time.Duration) (result []byte, err error) {
|
|
|
|
method = strings.ToUpper(method)
|
|
|
|
if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" {
|
|
|
|
return nil, errors.New("invalid http method")
|
|
|
|
}
|
|
|
|
if url == "" {
|
|
|
|
return nil, errors.New("request url can`t be empty")
|
|
|
|
}
|
|
|
|
client := &http.Client{}
|
|
|
|
if timeOut <= 0 {
|
|
|
|
client.Timeout = time.Second * 15
|
|
|
|
} else {
|
|
|
|
client.Timeout = timeOut
|
|
|
|
}
|
|
|
|
requestHandle, err := http.NewRequest(method, url, body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for k, v := range header {
|
|
|
|
requestHandle.Header.Set(k, v)
|
|
|
|
}
|
|
|
|
rsp, err := client.Do(requestHandle)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer rsp.Body.Close()
|
|
|
|
buff := bytes.Buffer{}
|
|
|
|
reader := bufio.NewReader(rsp.Body)
|
|
|
|
for {
|
2023-10-16 02:57:33 +00:00
|
|
|
line, err := reader.ReadBytes('\n')
|
2023-10-13 09:44:02 +00:00
|
|
|
if err != nil {
|
2023-10-16 02:57:33 +00:00
|
|
|
if err == io.EOF {
|
|
|
|
_, err = buff.Write(line)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
2023-10-13 09:44:02 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
_, err = buff.Write(line)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return buff.Bytes(), nil
|
|
|
|
}
|