claude.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package render
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/bytedance/sonic"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func ClaudeData(c *gin.Context, data []byte) {
  9. if len(c.Errors) > 0 {
  10. return
  11. }
  12. if c.IsAborted() {
  13. return
  14. }
  15. c.Render(-1, &Anthropic{Data: data})
  16. c.Writer.Flush()
  17. }
  18. func ClaudeEventData(c *gin.Context, event string, data []byte) {
  19. if len(c.Errors) > 0 {
  20. return
  21. }
  22. if c.IsAborted() {
  23. return
  24. }
  25. c.Render(-1, &Anthropic{Event: event, Data: data})
  26. c.Writer.Flush()
  27. }
  28. func ClaudeObjectData(c *gin.Context, object any) error {
  29. if len(c.Errors) > 0 {
  30. return c.Errors.Last()
  31. }
  32. if c.IsAborted() {
  33. return errors.New("context aborted")
  34. }
  35. jsonData, err := sonic.Marshal(object)
  36. if err != nil {
  37. return fmt.Errorf("error marshalling object: %w", err)
  38. }
  39. c.Render(-1, &Anthropic{Data: jsonData})
  40. c.Writer.Flush()
  41. return nil
  42. }
  43. func ClaudeEventObjectData(c *gin.Context, event string, object any) error {
  44. if len(c.Errors) > 0 {
  45. return c.Errors.Last()
  46. }
  47. if c.IsAborted() {
  48. return errors.New("context aborted")
  49. }
  50. jsonData, err := sonic.Marshal(object)
  51. if err != nil {
  52. return fmt.Errorf("error marshalling object: %w", err)
  53. }
  54. c.Render(-1, &Anthropic{Event: event, Data: jsonData})
  55. c.Writer.Flush()
  56. return nil
  57. }