common.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package render
  2. import (
  3. "bytes"
  4. "net/http"
  5. "slices"
  6. "github.com/labring/aiproxy/core/common/conv"
  7. )
  8. const (
  9. n = "\n"
  10. nn = "\n\n"
  11. event = "event: "
  12. data = "data: "
  13. )
  14. var (
  15. nBytes = conv.StringToBytes(n)
  16. nnBytes = conv.StringToBytes(nn)
  17. eventBytes = conv.StringToBytes(event)
  18. dataBytes = conv.StringToBytes(data)
  19. )
  20. const (
  21. DONE = "[DONE]"
  22. DataPrefix = "data:"
  23. DataPrefixLength = len(DataPrefix)
  24. )
  25. var (
  26. DataPrefixBytes = conv.StringToBytes(DataPrefix)
  27. DoneBytes = conv.StringToBytes(DONE)
  28. )
  29. // IsValidSSEData checks if data is valid SSE format
  30. func IsValidSSEData(data []byte) bool {
  31. return len(data) >= DataPrefixLength &&
  32. slices.Equal(data[:DataPrefixLength], DataPrefixBytes)
  33. }
  34. // ExtractSSEData extracts data from SSE format
  35. func ExtractSSEData(data []byte) []byte {
  36. return bytes.TrimSpace(data[DataPrefixLength:])
  37. }
  38. // IsSSEDone checks if SSE data indicates completion
  39. func IsSSEDone(data []byte) bool {
  40. return slices.Equal(data, DoneBytes)
  41. }
  42. func WriteSSEContentType(w http.ResponseWriter) {
  43. header := w.Header()
  44. if header.Get("Content-Type") == "text/event-stream" {
  45. return
  46. }
  47. header.Set("Content-Type", "text/event-stream")
  48. header.Set("Cache-Control", "no-cache")
  49. header.Set("Connection", "keep-alive")
  50. header.Set("Transfer-Encoding", "chunked")
  51. header.Set("X-Accel-Buffering", "no")
  52. }