fix
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package curl
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -32,3 +34,48 @@ func ApiCall(url, method string, header map[string]string, body io.Reader, timeO
|
||||
}
|
||||
return client.Do(requestHandle)
|
||||
}
|
||||
|
||||
// 请求(读取返回字节内容)
|
||||
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 {
|
||||
line, _, err := reader.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = buff.Write(line)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return buff.Bytes(), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user