acceleronixHttpClient.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package acceleronix
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fwh-toolbox-server/utils/httpClient"
  8. "net/http"
  9. "strconv"
  10. "time"
  11. "go.uber.org/zap"
  12. )
  13. // API文档地址:https://cmp.acceleronix.io/document/home
  14. const (
  15. mainUrl = "https://cmp.acceleronix.io/gateway/openapi"
  16. appKey = "0cE57qK03qsA9158"
  17. appSecret = "6051y5YS"
  18. timeout time.Duration = 30 * time.Second // SmartHub请求超时30s
  19. )
  20. var acceleronixHttpClient = httpClient.HttpClient{}
  21. func makeSignature(timestamp, requestBody string) string {
  22. message := appKey + timestamp + requestBody
  23. // 创建 HMAC-SHA256
  24. h := hmac.New(sha256.New, []byte(appSecret))
  25. // 写入数据
  26. h.Write([]byte(message))
  27. // 计算摘要
  28. signature := h.Sum(nil)
  29. // hex 编码
  30. return hex.EncodeToString(signature)
  31. }
  32. func bodyToStableString(body any) (string, error) {
  33. if body == nil {
  34. return "", nil
  35. }
  36. switch v := body.(type) {
  37. case string:
  38. return v, nil
  39. case []byte:
  40. return string(v), nil
  41. default:
  42. b, err := json.Marshal(v)
  43. if err != nil {
  44. return "", err
  45. }
  46. return string(b), nil
  47. }
  48. }
  49. func acceleronixHttpPost(url string, body any) (*httpClient.Response, error) {
  50. t := timeout
  51. timestamp := strconv.FormatInt(time.Now().Unix(), 10)
  52. bodyStr, err := bodyToStableString(body)
  53. if err != nil {
  54. zap.L().Error("body marshal failed.", zap.Any("body", body), zap.String("err", err.Error()))
  55. return nil, err
  56. }
  57. opt := httpClient.HttpClientOptions{
  58. Timeout: &t,
  59. Header: &http.Header{
  60. "APP-Key": {appKey},
  61. "Signature": {makeSignature(timestamp, bodyStr)},
  62. "Timestamp": {timestamp},
  63. "Accept": {"application/json", "text/plain", "*/*"},
  64. },
  65. }
  66. return acceleronixHttpClient.HttpPost(mainUrl+url, body, &opt)
  67. }