v1.go 5.0 KB

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