v1.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package v1
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "metawant.greentech.com.cn/gaoyagang/gt-common/datacenter_client"
  11. "metawant.greentech.com.cn/gaoyagang/gt-common/httplib"
  12. "net/http"
  13. "net/url"
  14. "time"
  15. )
  16. type (
  17. Opts func(name, value interface{})
  18. DcApi struct {
  19. options ClientOptions
  20. }
  21. // ClientOptions 客户端配置选项
  22. ClientOptions struct {
  23. httplib.HTTPSettings
  24. ServerIp string
  25. AppName string
  26. AppSecret string
  27. DoBefore []func(r *httplib.HTTPRequest) error
  28. DoAfter []func(r *httplib.HTTPRequest) error
  29. }
  30. )
  31. func NewDcApi(options ClientOptions) *DcApi {
  32. dcapi := &DcApi{}
  33. if len(options.DoBefore) == 0 {
  34. options.DoBefore = make([]func(r *httplib.HTTPRequest) error, 0)
  35. }
  36. options.DoBefore = append(options.DoBefore, dcapi.signMiddleware)
  37. dcapi.options = options
  38. return dcapi
  39. }
  40. // SetHttpSettings 设置客户端选择
  41. // ShowDebug bool
  42. // UserAgent string
  43. // TLSClientConfig *tls.Config
  44. // Proxy func(*http.Request) (*url.URL, error)
  45. // Transport http.RoundTripper
  46. // CheckRedirect func(req *http.Request, via []*http.Request) error
  47. // EnableCookie bool
  48. // Gzip bool
  49. // DumpBody bool
  50. // Retries int // if set to -1 means will retry forever
  51. // ConnectTimeout time.Duration
  52. // KeepAlive time.Duration
  53. // Timeout time.Duration
  54. func (d *DcApi) SetHttpSettings(settings httplib.HTTPSettings) {
  55. d.options.HTTPSettings = settings
  56. }
  57. func (d *DcApi) serviceUrl(serviceName string) string {
  58. return fmt.Sprintf("%s%s%s%s", "http://", d.options.ServerIp, "/api/dtgateway/v1", serviceName)
  59. }
  60. // 实际执行请求
  61. func (d *DcApi) call(r *httplib.HTTPRequest, resp interface{}) error {
  62. for _, bf := range d.options.DoBefore {
  63. if err := bf(r); err != nil {
  64. return err
  65. }
  66. }
  67. response, err := r.Response()
  68. if err != nil {
  69. return err
  70. }
  71. if response.StatusCode != http.StatusOK {
  72. msg, _ := r.String()
  73. return errors.New(fmt.Sprintf("response status code: %d, body: %s", response.StatusCode, msg))
  74. }
  75. if xerr := r.ToJSON(resp); err != nil {
  76. return errors.New(fmt.Sprintf("response to json error %s", xerr.Error()))
  77. }
  78. // 这里应该增加一个记录日志的after
  79. for _, af := range d.options.DoAfter {
  80. if err := af(r); err != nil {
  81. return err
  82. }
  83. }
  84. return nil
  85. }
  86. // 数据签名middleware
  87. func (d *DcApi) signMiddleware(r *httplib.HTTPRequest) error {
  88. // 验证公共参数
  89. if d.options.AppName == "" {
  90. return errors.New(fmt.Sprintf("error: %d app name empty", datacenter_client.DC_PARAMS_APP_NAME_MISSION))
  91. }
  92. if d.options.AppSecret == "" {
  93. return errors.New(fmt.Sprintf("error: %d app secret empty", datacenter_client.DC_PARAMS_APP_SECRET_MISSION))
  94. }
  95. queryParams := r.GetQueryParam()
  96. if pids, ok := queryParams["project_id"]; !ok || len(pids) == 0 {
  97. return errors.New(fmt.Sprintf("error: %d project id empty", datacenter_client.DC_PARAMS_PROJECT_ID_MISSION))
  98. } else {
  99. r.Param("project_id", pids[0])
  100. }
  101. r.Param("ts", fmt.Sprintf("%d", time.Now().Unix()))
  102. sign, err := CalcSign(r, d.options.AppSecret)
  103. if err != nil {
  104. return errors.New(fmt.Sprintf("error: %d check data sign error", datacenter_client.DC_DATA_SIGN_ERROR))
  105. }
  106. r.Param("sign", sign)
  107. // 设置headers信息
  108. r.Header("APP-NAME", d.options.AppName)
  109. return nil
  110. }
  111. func cutS2(s2 string) string {
  112. if s2 == "" {
  113. return ""
  114. }
  115. s2l := len(s2)
  116. //if s2l <= S2_MIN_LENGTH {
  117. // return s2
  118. //}
  119. return fmt.Sprintf("%s%s", s2[:datacenter_client.S2_HEAD_LENGTH], s2[s2l-datacenter_client.S2_TAIL_LENGTH:])
  120. }
  121. func sortS2(s2 string) (string, error) {
  122. if s2 == "" {
  123. return "", nil
  124. }
  125. var mi map[string]interface{}
  126. if err := json.Unmarshal([]byte(s2), &mi); err != nil {
  127. return "", err
  128. }
  129. //smi := SortMapByKey(mi)
  130. if bs, err := json.Marshal(mi); err != nil {
  131. return "", err
  132. } else {
  133. return string(bs), nil
  134. }
  135. }
  136. func CalcSign(r *httplib.HTTPRequest, secret string) (string, error) {
  137. s2, err := parseBody(r)
  138. if err != nil {
  139. fmt.Println("parseBody Error: ", err.Error())
  140. return "", err
  141. }
  142. contentLength := r.GetRequest().ContentLength
  143. if contentLength > datacenter_client.S2_MIN_LENGTH {
  144. r.Param("sign_flag", "1")
  145. s2 = cutS2(s2)
  146. } else {
  147. s2, err = sortS2(s2)
  148. if err != nil {
  149. return "", err
  150. }
  151. }
  152. s3 := contentLength
  153. s1 := parseQuery(r)
  154. m := md5.New()
  155. m.Write([]byte(fmt.Sprintf("%s%s%d%s", s1, s2, s3, secret)))
  156. md5Str := hex.EncodeToString(m.Sum(nil))
  157. //fmt.Println("s1", s1)
  158. //fmt.Println("s2", s2)
  159. //fmt.Println("s3", s3)
  160. //fmt.Println("md5", md5Str)
  161. return md5Str, nil
  162. }
  163. func parseBody(r *httplib.HTTPRequest) (s2 string, err error) {
  164. if r.GetRequest().Method == http.MethodGet {
  165. return "", nil
  166. }
  167. body := r.GetRequest().Body
  168. cnt, err := ioutil.ReadAll(body)
  169. if err != nil {
  170. return "", err
  171. }
  172. r.GetRequest().Body = ioutil.NopCloser(bytes.NewReader(cnt))
  173. return string(cnt), nil
  174. }
  175. func parseQuery(r *httplib.HTTPRequest) string {
  176. params := r.GetQueryParam()
  177. delete(params, "sign")
  178. val := url.Values{}
  179. for k, v := range params {
  180. for index, s := range v {
  181. if index == 0 {
  182. val.Set(k, s)
  183. } else {
  184. val.Add(k, s)
  185. }
  186. }
  187. }
  188. return val.Encode()
  189. }