1
0

http.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package pkg
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. )
  10. // 发送GET请求
  11. // url: 请求地址
  12. // response: 请求返回的内容
  13. func Get(url string) (string, error) {
  14. client := &http.Client{}
  15. req, err := http.NewRequest("GET", url, nil)
  16. req.Header.Set("Accept", "*/*")
  17. req.Header.Set("Content-Type", "application/json")
  18. if err != nil {
  19. return "", err
  20. }
  21. resp, err := client.Do(req)
  22. if err != nil {
  23. return "", err
  24. }
  25. defer resp.Body.Close()
  26. result, _ := ioutil.ReadAll(resp.Body)
  27. return string(result), nil
  28. }
  29. // 发送POST请求
  30. // url: 请求地址
  31. // data: POST请求提交的数据
  32. // contentType: 请求体格式,如:application/json
  33. // content: 请求放回的内容
  34. func Post(url string, data interface{}, contentType string) ([]byte, error) {
  35. // 超时时间:5秒
  36. client := &http.Client{Timeout: 5 * time.Second}
  37. jsonStr, _ := json.Marshal(data)
  38. resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
  39. if err != nil {
  40. return nil, err
  41. }
  42. defer resp.Body.Close()
  43. result, _ := io.ReadAll(resp.Body)
  44. return result, nil
  45. }