webhook.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package server
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/langgenius/dify-plugin-daemon/internal/db"
  5. "github.com/langgenius/dify-plugin-daemon/internal/service"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  7. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  8. )
  9. // DifyPlugin supports register and use webhook to improve the plugin's functionality
  10. // you can use it to do some magic things, look forward to your imagination Ciallo~(∠·ω< )⌒
  11. // - Yeuoly
  12. // WebhookHandler is a function type that can be used to handle webhook requests
  13. type WebhookHandler func(ctx *gin.Context, hook_id string, path string)
  14. func (app *App) Webhook() func(c *gin.Context) {
  15. return func(c *gin.Context) {
  16. hook_id := c.Param("hook_id")
  17. path := c.Param("path")
  18. if app.webhook_handler != nil {
  19. app.webhook_handler(c, hook_id, path)
  20. } else {
  21. app.WebhookHandler(c, hook_id, path)
  22. }
  23. }
  24. }
  25. func (app *App) WebhookHandler(ctx *gin.Context, hook_id string, path string) {
  26. webhook, err := db.GetOne[models.Webhook](
  27. db.Equal("hook_id", hook_id),
  28. )
  29. if err == db.ErrDatabaseNotFound {
  30. ctx.JSON(404, gin.H{"error": "webhook not found"})
  31. return
  32. }
  33. if err != nil {
  34. log.Error("get webhook error %v", err)
  35. ctx.JSON(500, gin.H{"error": "internal server error"})
  36. return
  37. }
  38. // check if plugin exists in current node
  39. if !app.cluster.IsPluginNoCurrentNode(webhook.PluginID) {
  40. app.Redirect(ctx, webhook.PluginID)
  41. } else {
  42. service.Webhook(ctx, &webhook, path)
  43. }
  44. }