billing_expr_request.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package helper
  2. import (
  3. "strings"
  4. "github.com/QuantumNous/new-api/common"
  5. "github.com/QuantumNous/new-api/dto"
  6. "github.com/QuantumNous/new-api/pkg/billingexpr"
  7. relaycommon "github.com/QuantumNous/new-api/relay/common"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func ResolveIncomingBillingExprRequestInput(c *gin.Context, info *relaycommon.RelayInfo) (billingexpr.RequestInput, error) {
  11. if info != nil && info.BillingRequestInput != nil {
  12. input := cloneRequestInput(*info.BillingRequestInput)
  13. merged := cloneStringMap(info.RequestHeaders)
  14. for k, v := range input.Headers {
  15. merged[k] = v
  16. }
  17. input.Headers = merged
  18. return input, nil
  19. }
  20. input := billingexpr.RequestInput{}
  21. if info != nil {
  22. input.Headers = cloneStringMap(info.RequestHeaders)
  23. }
  24. bodyBytes, err := readIncomingBillingExprBody(c)
  25. if err != nil {
  26. return billingexpr.RequestInput{}, err
  27. }
  28. input.Body = bodyBytes
  29. return input, nil
  30. }
  31. func BuildBillingExprRequestInputFromRequest(request dto.Request, headers map[string]string) (billingexpr.RequestInput, error) {
  32. input := billingexpr.RequestInput{
  33. Headers: cloneStringMap(headers),
  34. }
  35. if request == nil {
  36. return input, nil
  37. }
  38. bodyBytes, err := common.Marshal(request)
  39. if err != nil {
  40. return billingexpr.RequestInput{}, err
  41. }
  42. input.Body = bodyBytes
  43. return input, nil
  44. }
  45. func readIncomingBillingExprBody(c *gin.Context) ([]byte, error) {
  46. if c == nil || c.Request == nil || !isJSONContentType(c.Request.Header.Get("Content-Type")) {
  47. return nil, nil
  48. }
  49. storage, err := common.GetBodyStorage(c)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return storage.Bytes()
  54. }
  55. func cloneRequestInput(src billingexpr.RequestInput) billingexpr.RequestInput {
  56. input := billingexpr.RequestInput{
  57. Headers: cloneStringMap(src.Headers),
  58. }
  59. if len(src.Body) > 0 {
  60. input.Body = append([]byte(nil), src.Body...)
  61. }
  62. return input
  63. }
  64. func isJSONContentType(contentType string) bool {
  65. contentType = strings.ToLower(strings.TrimSpace(contentType))
  66. return strings.HasPrefix(contentType, "application/json")
  67. }
  68. func cloneStringMap(src map[string]string) map[string]string {
  69. if len(src) == 0 {
  70. return map[string]string{}
  71. }
  72. dst := make(map[string]string, len(src))
  73. for key, value := range src {
  74. if strings.TrimSpace(key) == "" {
  75. continue
  76. }
  77. dst[key] = value
  78. }
  79. return dst
  80. }