newLineSplitter returns a bufio.SplitFunc for SSE lines. The specification (9.2.5) allows three line endings: CR LF ("\r\n"), a lone LF ("\n"), or a lone CR ("\r"), where CR is U+000D CARRIAGE RETURN and LF is U+000A LINE FEED. A CR is ambiguous until the next byte arrives: it either ends the line
()
| 135 | // |
| 136 | // The Event Subscriptions API ends every line with a lone LF, so CR handling is only there for spec compliance. |
| 137 | func newLineSplitter() bufio.SplitFunc { |
| 138 | var skipLF bool |
| 139 | return func(data []byte, atEOF bool) (int, []byte, error) { |
| 140 | // The skipped LF is consumed in the same call rather than returned on its own: a nil token makes the Scanner |
| 141 | // read again before splitting what it has buffered, which would hold back a complete line until more arrives. |
| 142 | var skipped int |
| 143 | if skipLF && len(data) > 0 { |
| 144 | skipLF = false |
| 145 | if data[0] == '\n' { |
| 146 | skipped = 1 |
| 147 | data = data[1:] |
| 148 | } |
| 149 | } |
| 150 | if i := bytes.IndexAny(data, "\r\n"); i >= 0 { |
| 151 | if data[i] == '\r' { |
| 152 | if i+1 < len(data) { |
| 153 | if data[i+1] == '\n' { |
| 154 | return skipped + i + 2, data[:i], nil |
| 155 | } |
| 156 | } else { |
| 157 | skipLF = true |
| 158 | } |
| 159 | } |
| 160 | return skipped + i + 1, data[:i], nil |
| 161 | } |
| 162 | if atEOF && len(data) > 0 { |
| 163 | return skipped + len(data), data, nil |
| 164 | } |
| 165 | return skipped, nil, nil |
| 166 | } |
| 167 | } |