123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- package main
- import (
- "bytes"
- "fmt"
- "io/ioutil"
- "net/http"
- "time"
- )
- // HTTPRequest 用于发送 HTTP 请求
- func HTTPRequest(method, url string, headers map[string]string, body []byte) (string, error) {
- // 创建一个新的 HTTP 请求
- client := &http.Client{
- Timeout: 10 * time.Second, // 设置请求超时时间
- }
- // 创建 HTTP 请求
- req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
- if err != nil {
- return "", fmt.Errorf("failed to create request: %v", err)
- }
- // 设置请求头
- for key, value := range headers {
- req.Header.Set(key, value)
- }
- // 发送请求
- resp, err := client.Do(req)
- if err != nil {
- return "", fmt.Errorf("failed to send request: %v", err)
- }
- defer resp.Body.Close()
- // 读取响应体
- respBody, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return "", fmt.Errorf("failed to read response body: %v", err)
- }
- // 如果响应状态码不是 200,则返回错误
- if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("request failed with status: %d", resp.StatusCode)
- }
- return string(respBody), nil
- }
|