43 lines
837 B
Go
43 lines
837 B
Go
package utils
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// HttpRequest 发送 HTTP 请求
|
|
func HttpRequest(method, url string, headers map[string]string, body []byte) ([]byte, error) {
|
|
client := &http.Client{
|
|
Timeout: 30 * time.Second, // 设置超时时间
|
|
}
|
|
|
|
// 创建请求
|
|
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 设置请求头
|
|
for key, value := range headers {
|
|
req.Header.Set(key, value)
|
|
}
|
|
|
|
// 发送请求
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
// 检查响应状态码
|
|
rBody, err := io.ReadAll(resp.Body)
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(rBody))
|
|
}
|
|
|
|
// 读取响应
|
|
return rBody, err
|
|
}
|