provincial_department.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package thirdparty
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. hurl "net/url"
  9. "github.com/jaryhe/gopkgs/logger"
  10. jsoniter "github.com/json-iterator/go"
  11. "go.uber.org/zap"
  12. )
  13. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  14. func ProvincialPost(api string, accessToken string, data map[string]interface{}) (result []byte, err error) {
  15. defer func() {
  16. req, _ := json.MarshalToString(data)
  17. resultStr := ""
  18. if result != nil {
  19. resultStr = string(result)
  20. }
  21. logger.Info("thirdparty",
  22. zap.String("api", api),
  23. zap.String("request", req),
  24. zap.String("response", resultStr))
  25. }()
  26. if accessToken != "" {
  27. api = fmt.Sprintf("%s?access_token=%s", api, accessToken)
  28. }
  29. dataBytes, _ := json.Marshal(data)
  30. req, err := http.NewRequest("POST", api, bytes.NewReader(dataBytes))
  31. client := &http.Client{}
  32. client.Timeout = time.Duration(30) * time.Second
  33. resp, err := client.Do(req)
  34. if err != nil {
  35. return nil, err
  36. }
  37. if resp.StatusCode != http.StatusOK {
  38. return nil, fmt.Errorf("wrong status code: %d", resp.StatusCode)
  39. }
  40. defer resp.Body.Close()
  41. result, err = ioutil.ReadAll(resp.Body)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return result, nil
  46. }
  47. func ProvincialGet(api string, accessToken string, data map[string]string) (result []byte, err error) {
  48. defer func() {
  49. req, _ := json.MarshalToString(data)
  50. resultStr := ""
  51. if result != nil {
  52. resultStr = string(result)
  53. }
  54. logger.Info("thirdparty",
  55. zap.String("api", api),
  56. zap.String("request", req),
  57. zap.String("response", resultStr))
  58. }()
  59. api = fmt.Sprintf("%s?access_token=%s", api, accessToken)
  60. if len(data) > 0 {
  61. var value hurl.Values
  62. for k, v := range data {
  63. value.Add(k, v)
  64. }
  65. api = fmt.Sprintf("%s&%s", api, value.Encode())
  66. }
  67. req, err := http.NewRequest("GET", api, nil)
  68. client := &http.Client{}
  69. client.Timeout = time.Duration(30) * time.Second
  70. resp, err := client.Do(req)
  71. if err != nil {
  72. return nil, err
  73. }
  74. if resp.StatusCode != http.StatusOK {
  75. return nil, fmt.Errorf("wrong status code: %d", resp.StatusCode)
  76. }
  77. defer resp.Body.Close()
  78. result, err = ioutil.ReadAll(resp.Body)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return result, nil
  83. }