http.go 920 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package net
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "github.com/go-resty/resty/v2"
  7. )
  8. func HttpGet(url string) []byte {
  9. client := resty.New().SetTimeout(time.Second * 3)
  10. resp, err := client.R().
  11. EnableTrace().
  12. Get(url)
  13. if err != nil {
  14. fmt.Println(err)
  15. return nil
  16. }
  17. return resp.Body()
  18. }
  19. func HttpPost(url string, body interface{}) []byte {
  20. resp, err := resty.New().SetTimeout(time.Second*3).R().
  21. SetHeader("Content-Type", "application/json").
  22. SetBody(body).
  23. Post(url)
  24. if err != nil {
  25. fmt.Println(err)
  26. return nil
  27. }
  28. return resp.Body()
  29. }
  30. func HttpGetJSON(url string, response interface{}) (err error) {
  31. resp := HttpGet(url)
  32. err = json.Unmarshal(resp, response)
  33. return
  34. }
  35. func HttpPostJSON(url string, request, response interface{}) (err error) {
  36. body, err := json.Marshal(request)
  37. if err != nil {
  38. return
  39. }
  40. resp := HttpPost(url, body)
  41. err = json.Unmarshal(resp, response)
  42. return
  43. }