base.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package controllers
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/langgenius/dify-plugin-daemon/internal/server/constants"
  5. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  7. "github.com/langgenius/dify-plugin-daemon/internal/types/validators"
  8. )
  9. func BindRequest[T any](r *gin.Context, success func(T)) {
  10. var request T
  11. var err error
  12. context_type := r.GetHeader("Content-Type")
  13. if context_type == "application/json" {
  14. err = r.ShouldBindJSON(&request)
  15. } else {
  16. err = r.ShouldBind(&request)
  17. }
  18. if err != nil {
  19. resp := entities.NewErrorResponse(-400, err.Error())
  20. r.JSON(400, resp)
  21. return
  22. }
  23. // validate, we have customized some validators which are not supported by gin binding
  24. if err := validators.GlobalEntitiesValidator.Struct(request); err != nil {
  25. resp := entities.NewErrorResponse(-400, err.Error())
  26. r.JSON(400, resp)
  27. return
  28. }
  29. success(request)
  30. }
  31. func BindRequestWithPluginUniqueIdentifier[T any](r *gin.Context, success func(
  32. T, plugin_entities.PluginUniqueIdentifier,
  33. )) {
  34. BindRequest(r, func(req T) {
  35. plugin_unique_identifier := r.GetHeader(constants.X_PLUGIN_IDENTIFIER)
  36. if plugin_unique_identifier == "" {
  37. resp := entities.NewErrorResponse(-400, "Plugin unique identifier is required")
  38. r.JSON(400, resp)
  39. return
  40. }
  41. identifier, err := plugin_entities.NewPluginUniqueIdentifier(plugin_unique_identifier)
  42. if err != nil {
  43. resp := entities.NewErrorResponse(-400, err.Error())
  44. r.JSON(400, resp)
  45. return
  46. }
  47. success(req, identifier)
  48. })
  49. }