http.go 1.1 KB

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