base.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if r.Request.Header.Get("Content-Type") == "application/json" {
  13. err = r.ShouldBindJSON(&request)
  14. } else {
  15. err = r.ShouldBind(&request)
  16. }
  17. if err != nil {
  18. resp := entities.NewErrorResponse(-400, err.Error())
  19. r.JSON(400, resp)
  20. return
  21. }
  22. // bind uri
  23. err = r.ShouldBindUri(&request)
  24. if err != nil {
  25. resp := entities.NewErrorResponse(-400, err.Error())
  26. r.JSON(400, resp)
  27. return
  28. }
  29. // validate, we have customized some validators which are not supported by gin binding
  30. if err := validators.GlobalEntitiesValidator.Struct(request); err != nil {
  31. resp := entities.NewErrorResponse(-400, err.Error())
  32. r.JSON(400, resp)
  33. return
  34. }
  35. success(request)
  36. }
  37. func BindRequestWithPluginUniqueIdentifier[T any](r *gin.Context, success func(
  38. T, plugin_entities.PluginUniqueIdentifier,
  39. )) {
  40. BindRequest(r, func(req T) {
  41. plugin_unique_identifier := r.GetHeader(constants.X_PLUGIN_IDENTIFIER)
  42. if plugin_unique_identifier == "" {
  43. resp := entities.NewErrorResponse(-400, "Plugin unique identifier is required")
  44. r.JSON(400, resp)
  45. return
  46. }
  47. identifier, err := plugin_entities.NewPluginUniqueIdentifier(plugin_unique_identifier)
  48. if err != nil {
  49. resp := entities.NewErrorResponse(-400, err.Error())
  50. r.JSON(400, resp)
  51. return
  52. }
  53. success(req, identifier)
  54. })
  55. }