billing_expr_request.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package helper
  2. import (
  3. "strings"
  4. "github.com/QuantumNous/new-api/common"
  5. "github.com/QuantumNous/new-api/pkg/billingexpr"
  6. relaycommon "github.com/QuantumNous/new-api/relay/common"
  7. "github.com/gin-gonic/gin"
  8. )
  9. func ResolveIncomingBillingExprRequestInput(c *gin.Context, info *relaycommon.RelayInfo) (billingexpr.RequestInput, error) {
  10. input := billingexpr.RequestInput{}
  11. if info != nil {
  12. input.Headers = cloneStringMap(info.RequestHeaders)
  13. }
  14. bodyBytes, err := readIncomingBillingExprBody(c)
  15. if err != nil {
  16. return billingexpr.RequestInput{}, err
  17. }
  18. input.Body = bodyBytes
  19. return input, nil
  20. }
  21. func readIncomingBillingExprBody(c *gin.Context) ([]byte, error) {
  22. if c == nil || c.Request == nil || !isJSONContentType(c.Request.Header.Get("Content-Type")) {
  23. return nil, nil
  24. }
  25. storage, err := common.GetBodyStorage(c)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return storage.Bytes()
  30. }
  31. func isJSONContentType(contentType string) bool {
  32. contentType = strings.ToLower(strings.TrimSpace(contentType))
  33. return strings.HasPrefix(contentType, "application/json")
  34. }
  35. func cloneStringMap(src map[string]string) map[string]string {
  36. if len(src) == 0 {
  37. return map[string]string{}
  38. }
  39. dst := make(map[string]string, len(src))
  40. for key, value := range src {
  41. if strings.TrimSpace(key) == "" {
  42. continue
  43. }
  44. dst[key] = value
  45. }
  46. return dst
  47. }