acceleronixHttpClient.go 1.7 KB

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