mail_api_client.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package client
  2. import (
  3. "context"
  4. "encoding/json"
  5. xhttp "net/http"
  6. "strings"
  7. bm "go-common/library/net/http/blademaster"
  8. pkgerr "github.com/pkg/errors"
  9. )
  10. const (
  11. _contentTypeJSON = "application/json"
  12. )
  13. //Client client is http client.
  14. type Client struct {
  15. client *bm.Client
  16. }
  17. // NewClient new a http client.
  18. func NewClient(client *bm.Client) *Client {
  19. cl := new(Client)
  20. cl.client = client
  21. return cl
  22. }
  23. // Get a json req http get.
  24. func (client *Client) Get(c context.Context, uri string, params interface{}, res interface{}) (err error) {
  25. req, err := client.NewRequest(xhttp.MethodGet, uri, params)
  26. if err != nil {
  27. return
  28. }
  29. return client.client.Do(c, req, res)
  30. }
  31. // Post a json req http post.
  32. func (client *Client) Post(c context.Context, uri string, params interface{}, res interface{}) (err error) {
  33. req, err := client.NewRequest(xhttp.MethodPost, uri, params)
  34. if err != nil {
  35. return
  36. }
  37. return client.client.Do(c, req, res)
  38. }
  39. // NewRequest new http request with method, uri, ip, values and headers.
  40. func (client *Client) NewRequest(method, uri string, params interface{}) (req *xhttp.Request, err error) {
  41. marshal, err := json.Marshal(params)
  42. if err != nil {
  43. err = pkgerr.Wrapf(err, "marshal:%v", params)
  44. return
  45. }
  46. req, err = xhttp.NewRequest(method, uri, strings.NewReader(string(marshal)))
  47. if err != nil {
  48. err = pkgerr.Wrapf(err, "method:%s,uri:%s", method, string(marshal))
  49. return
  50. }
  51. req.Header.Set("Content-Type", _contentTypeJSON)
  52. return
  53. }