tools.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. )
  9. // HTTPRequest 用于发送 HTTP 请求
  10. func HTTPRequest(method, url string, headers map[string]string, body []byte) (string, error) {
  11. // 创建一个新的 HTTP 请求
  12. client := &http.Client{
  13. Timeout: 10 * time.Second, // 设置请求超时时间
  14. }
  15. // 创建 HTTP 请求
  16. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  17. if err != nil {
  18. return "", fmt.Errorf("failed to create request: %v", err)
  19. }
  20. // 设置请求头
  21. for key, value := range headers {
  22. req.Header.Set(key, value)
  23. }
  24. // 发送请求
  25. resp, err := client.Do(req)
  26. if err != nil {
  27. return "", fmt.Errorf("failed to send request: %v", err)
  28. }
  29. defer resp.Body.Close()
  30. // 读取响应体
  31. respBody, err := ioutil.ReadAll(resp.Body)
  32. if err != nil {
  33. return "", fmt.Errorf("failed to read response body: %v", err)
  34. }
  35. // 如果响应状态码不是 200,则返回错误
  36. if resp.StatusCode != http.StatusOK {
  37. return "", fmt.Errorf("request failed with status: %d", resp.StatusCode)
  38. }
  39. return string(respBody), nil
  40. }