| 33 | } |
| 34 | |
| 35 | func (p *SSEParser) Parse(reader io.Reader) error { |
| 36 | scanner := bufio.NewScanner(reader) |
| 37 | |
| 38 | var currentEvent SSEEvent |
| 39 | var dataLines []string |
| 40 | |
| 41 | for scanner.Scan() { |
| 42 | line := scanner.Text() |
| 43 | |
| 44 | // Empty line indicates end of event |
| 45 | if line == "" { |
| 46 | if len(dataLines) > 0 { |
| 47 | currentEvent.Data = strings.Join(dataLines, "\n") |
| 48 | } |
| 49 | |
| 50 | // Default to message type if no event type specified |
| 51 | if currentEvent.Type == "" { |
| 52 | currentEvent.Type = SSEEventTypeMessage |
| 53 | } |
| 54 | |
| 55 | // Store the event |
| 56 | p.mu.Lock() |
| 57 | p.events[currentEvent.Type] = append(p.events[currentEvent.Type], currentEvent) |
| 58 | p.mu.Unlock() |
| 59 | |
| 60 | // Reset for next event |
| 61 | currentEvent = SSEEvent{} |
| 62 | dataLines = nil |
| 63 | continue |
| 64 | } |
| 65 | |
| 66 | // Skip comments |
| 67 | if strings.HasPrefix(line, ":") { |
| 68 | continue |
| 69 | } |
| 70 | |
| 71 | // Parse field:value format |
| 72 | if colonIndex := strings.Index(line, ":"); colonIndex != -1 { |
| 73 | field := line[:colonIndex] |
| 74 | value := line[colonIndex+1:] |
| 75 | |
| 76 | // Remove leading space from value if present |
| 77 | if len(value) > 0 && value[0] == ' ' { |
| 78 | value = value[1:] |
| 79 | } |
| 80 | |
| 81 | switch field { |
| 82 | case "event": |
| 83 | currentEvent.Type = value |
| 84 | case "data": |
| 85 | dataLines = append(dataLines, value) |
| 86 | case "id": |
| 87 | currentEvent.ID = value |
| 88 | case "retry": |
| 89 | if retryMs, err := strconv.Atoi(value); err == nil { |
| 90 | currentEvent.Retry = retryMs |
| 91 | } |
| 92 | } |