billing_expr_request.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. if len(input.Headers) == 0 {
  14. input.Headers = cloneStringMap(info.RequestHeaders)
  15. }
  16. return input, nil
  17. }
  18. input := billingexpr.RequestInput{}
  19. if info != nil {
  20. input.Headers = cloneStringMap(info.RequestHeaders)
  21. }
  22. bodyBytes, err := readIncomingBillingExprBody(c)
  23. if err != nil {
  24. return billingexpr.RequestInput{}, err
  25. }
  26. input.Body = bodyBytes
  27. return input, nil
  28. }
  29. func BuildBillingExprRequestInputFromRequest(request dto.Request, headers map[string]string) (billingexpr.RequestInput, error) {
  30. input := billingexpr.RequestInput{
  31. Headers: cloneStringMap(headers),
  32. }
  33. if request == nil {
  34. return input, nil
  35. }
  36. bodyBytes, err := common.Marshal(request)
  37. if err != nil {
  38. return billingexpr.RequestInput{}, err
  39. }
  40. input.Body = bodyBytes
  41. return input, nil
  42. }
  43. func readIncomingBillingExprBody(c *gin.Context) ([]byte, error) {
  44. if c == nil || c.Request == nil || !isJSONContentType(c.Request.Header.Get("Content-Type")) {
  45. return nil, nil
  46. }
  47. storage, err := common.GetBodyStorage(c)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return storage.Bytes()
  52. }
  53. func cloneRequestInput(src billingexpr.RequestInput) billingexpr.RequestInput {
  54. input := billingexpr.RequestInput{
  55. Headers: cloneStringMap(src.Headers),
  56. }
  57. if len(src.Body) > 0 {
  58. input.Body = append([]byte(nil), src.Body...)
  59. }
  60. return input
  61. }
  62. func isJSONContentType(contentType string) bool {
  63. contentType = strings.ToLower(strings.TrimSpace(contentType))
  64. return strings.HasPrefix(contentType, "application/json")
  65. }
  66. func cloneStringMap(src map[string]string) map[string]string {
  67. if len(src) == 0 {
  68. return map[string]string{}
  69. }
  70. dst := make(map[string]string, len(src))
  71. for key, value := range src {
  72. if strings.TrimSpace(key) == "" {
  73. continue
  74. }
  75. dst[key] = value
  76. }
  77. return dst
  78. }