base.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package controllers
  2. import (
  3. "errors"
  4. "github.com/gin-gonic/gin"
  5. "github.com/langgenius/dify-plugin-daemon/internal/server/constants"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/exception"
  7. "github.com/langgenius/dify-plugin-daemon/pkg/entities/plugin_entities"
  8. "github.com/langgenius/dify-plugin-daemon/pkg/validators"
  9. )
  10. func BindRequest[T any](r *gin.Context, success func(T)) {
  11. var request T
  12. if r.Request.Header.Get("Content-Type") == "application/json" {
  13. r.ShouldBindJSON(&request)
  14. } else {
  15. r.ShouldBind(&request)
  16. }
  17. // bind uri
  18. r.ShouldBindUri(&request)
  19. // validate, we have customized some validators which are not supported by gin binding
  20. if err := validators.GlobalEntitiesValidator.Struct(request); err != nil {
  21. r.JSON(400, exception.BadRequestError(err).ToResponse())
  22. return
  23. }
  24. success(request)
  25. }
  26. func BindPluginDispatchRequest[T any](r *gin.Context, success func(
  27. plugin_entities.InvokePluginRequest[T],
  28. )) {
  29. BindRequest(r, func(req plugin_entities.InvokePluginRequest[T]) {
  30. pluginUniqueIdentifierAny, exists := r.Get(constants.CONTEXT_KEY_PLUGIN_UNIQUE_IDENTIFIER)
  31. if !exists {
  32. r.JSON(400, exception.UniqueIdentifierError(errors.New("Plugin unique identifier is required")).ToResponse())
  33. return
  34. }
  35. pluginUniqueIdentifier, ok := pluginUniqueIdentifierAny.(plugin_entities.PluginUniqueIdentifier)
  36. if !ok {
  37. r.JSON(400, exception.UniqueIdentifierError(errors.New("Plugin unique identifier is not valid")).ToResponse())
  38. return
  39. }
  40. // set plugin unique identifier
  41. req.UniqueIdentifier = pluginUniqueIdentifier
  42. success(req)
  43. })
  44. }