client.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package http
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/pkg/errors"
  8. "kpt.notice/pkg/log"
  9. )
  10. type Client struct {
  11. client *http.Client
  12. }
  13. func NewClient(timeout time.Duration) *Client {
  14. return &Client{
  15. client: &http.Client{
  16. Timeout: timeout,
  17. },
  18. }
  19. }
  20. func HttpPost(url, contentType, body string) (resp *http.Response, err error) {
  21. // body := `{"userinfo":"tmr.shengmu23.bbc","openid":"123"}`
  22. // url :="http://kpttest.kptyun.com/userwxopenid/binding"
  23. // contentType:="application/json"
  24. log.Infof("pkg.http.HttpPost{url:%s,contentType:%s,body:%s}", url, contentType, body)
  25. resp, err = http.Post(url, contentType, strings.NewReader(body))
  26. if err != nil {
  27. err = errors.Wrap(err, "http.HttpPost")
  28. return
  29. }
  30. defer resp.Body.Close()
  31. return
  32. }
  33. func HttpGet(url string, params map[string]string) (body []byte, err error) {
  34. // url :="http://kpttest.kptyun.com/userwxopenid/binding"
  35. // contentType:="application/json"
  36. // params := map[string]string{"userinfo":"tmr.shengmu23.bbc","openid":"123"}
  37. s := make([]string, len(params))
  38. for k, v := range params {
  39. s = append(s, k+"="+v)
  40. }
  41. url = url + "?" + strings.Join(s, "&")
  42. resp, e := http.Get(url)
  43. if e != nil {
  44. err = errors.Wrap(e, "pkg.http.HttpGet==")
  45. return
  46. }
  47. body, e = ioutil.ReadAll(resp.Body)
  48. if e != nil {
  49. err = errors.Wrap(e, "pkg.http.HttpGet.read==")
  50. return
  51. }
  52. defer resp.Body.Close()
  53. return
  54. }