refactor(messages): keep the Anthropic event framing beside its only caller

sse.go now matches main. writeEvent and its prefix live in
messages_stream.go, the only code that writes named events.
This commit is contained in:
2026-11-27 01:38:24 +00:00
parent fabe72f77a
commit 043286f6db
2 changed files with 28 additions and 27 deletions
+28
View File
@@ -10,6 +10,9 @@ import (
"strings"
)
// sseEventPrefix is the SSE "event:" field prefix.
const sseEventPrefix = "event: "
// anthropicStreamErrorType is the error.type of an in-stream Anthropic error event.
const anthropicStreamErrorType = "api_error"
@@ -401,3 +404,28 @@ func relayAnthropicMessagesStream(w http.ResponseWriter, body io.Reader, model s
}
return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err)
}
// writeEvent writes one frame with an "event:" line ahead of the data, the
// framing the Anthropic Messages stream uses. event must not contain a line
// terminator; an empty event writes a bare data frame.
func (s *sseWriter) writeEvent(event string, b []byte) error {
if event == "" {
return s.writeData(b)
}
buf := append([]byte(sseEventPrefix), event...)
buf = append(buf, '\n')
for _, line := range splitSSELines(b) {
buf = append(buf, sseDataPrefix...)
buf = append(buf, line...)
buf = append(buf, '\n')
}
buf = append(buf, '\n')
if _, err := s.w.Write(buf); err != nil {
return err
}
if s.f != nil {
s.f.Flush()
}
return nil
}
-27
View File
@@ -55,8 +55,6 @@ var errSSEEventTooLarge = errors.New("llmgateway: sse event data exceeded the ma
// event payload, per the text/event-stream wire format.
const sseDataPrefix = "data: "
const sseEventPrefix = "event: "
// sseBOM is the UTF-8 byte-order mark. Some proxies still add one at the
// start of a stream. Left in place, it attaches to the first field name.
// "data:" becomes "\ufeffdata:", and readSSE drops the first event as an
@@ -287,31 +285,6 @@ func splitSSELines(b []byte) [][]byte {
}
}
// writeEvent writes one frame with an "event:" line ahead of the data, the
// framing the Anthropic Messages stream uses. event must not contain a line
// terminator; an empty event writes a bare data frame.
func (s *sseWriter) writeEvent(event string, b []byte) error {
if event == "" {
return s.writeData(b)
}
buf := append([]byte(sseEventPrefix), event...)
buf = append(buf, '\n')
for _, line := range splitSSELines(b) {
buf = append(buf, sseDataPrefix...)
buf = append(buf, line...)
buf = append(buf, '\n')
}
buf = append(buf, '\n')
if _, err := s.w.Write(buf); err != nil {
return err
}
if s.f != nil {
s.f.Flush()
}
return nil
}
// writeData writes one SSE data event as a single Write call, flushing
// when the underlying writer supports that.
//