http.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. )
  10. func Get[T any](url string) (*T, error) {
  11. return get[T](url)
  12. }
  13. func get[T any](url string) (*T, error) {
  14. obj := new(T)
  15. resp, err := http.Get(url)
  16. if err != nil {
  17. return obj, err
  18. }
  19. defer resp.Body.Close() // 确保在函数结束时关闭响应体
  20. // 检查响应状态码
  21. if resp.StatusCode != http.StatusOK {
  22. return obj, fmt.Errorf("error:%d", resp.StatusCode)
  23. }
  24. // 读取响应体
  25. body, err := ioutil.ReadAll(resp.Body)
  26. if err != nil {
  27. return obj, err
  28. }
  29. err = json.Unmarshal(body, &obj)
  30. return obj, err
  31. }
  32. func POST[T any](url string, data []byte) (*T, error) {
  33. return post[T](url, data)
  34. }
  35. func post[T any](uri string, data []byte) (*T, error) {
  36. obj := new(T)
  37. // 创建一个新的 POST 请求
  38. req, err := http.NewRequest("POST", uri, bytes.NewBuffer(data))
  39. if err != nil {
  40. return obj, err
  41. }
  42. // 设置请求头
  43. req.Header.Set("Content-Type", "application/json")
  44. // 发送请求
  45. client := &http.Client{}
  46. resp, err := client.Do(req)
  47. if err != nil {
  48. return obj, err
  49. }
  50. defer resp.Body.Close()
  51. // 读取响应
  52. body, err := io.ReadAll(resp.Body)
  53. if err != nil {
  54. return obj, err
  55. }
  56. err = json.Unmarshal(body, &obj)
  57. return obj, err
  58. }