kling_adapter.go 978 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package middleware
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "one-api/common"
  8. )
  9. func KlingRequestConvert() func(c *gin.Context) {
  10. return func(c *gin.Context) {
  11. var originalReq map[string]interface{}
  12. if err := common.UnmarshalBodyReusable(c, &originalReq); err != nil {
  13. c.Next()
  14. return
  15. }
  16. model, _ := originalReq["model"].(string)
  17. prompt, _ := originalReq["prompt"].(string)
  18. unifiedReq := map[string]interface{}{
  19. "model": model,
  20. "prompt": prompt,
  21. "metadata": originalReq,
  22. }
  23. jsonData, err := json.Marshal(unifiedReq)
  24. if err != nil {
  25. c.Next()
  26. return
  27. }
  28. // Rewrite request body and path
  29. c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonData))
  30. c.Request.URL.Path = "/v1/video/generations"
  31. if image := originalReq["image"]; image == "" {
  32. c.Set("action", "textGenerate")
  33. }
  34. // We have to reset the request body for the next handlers
  35. c.Set(common.KeyRequestBody, jsonData)
  36. c.Next()
  37. }
  38. }