Write 收集扫描结果,同时实时写入备份文件
(result *ScanResult)
| 479 | |
| 480 | // Write 收集扫描结果,同时实时写入备份文件 |
| 481 | func (w *JSONWriter) Write(result *ScanResult) error { |
| 482 | w.mu.Lock() |
| 483 | defer w.mu.Unlock() |
| 484 | |
| 485 | if w.closed { |
| 486 | return fmt.Errorf("writer is closed") |
| 487 | } |
| 488 | if result == nil { |
| 489 | return fmt.Errorf("result cannot be nil") |
| 490 | } |
| 491 | |
| 492 | // 1. 加入内存分类缓冲(用于最终有序输出) |
| 493 | w.buffer.Add(result) |
| 494 | |
| 495 | // 2. 实时写入备份文件(NDJSON格式,防崩溃丢失) |
| 496 | if w.realtimeFile != nil { |
| 497 | data, err := json.Marshal(result) |
| 498 | if err != nil { |
| 499 | return fmt.Errorf("failed to marshal result: %w", err) |
| 500 | } |
| 501 | if _, err := w.realtimeFile.Write(append(data, '\n')); err != nil { |
| 502 | return fmt.Errorf("failed to write realtime backup: %w", err) |
| 503 | } |
| 504 | if err := w.realtimeFile.Sync(); err != nil { |
| 505 | return fmt.Errorf("failed to sync realtime backup: %w", err) |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | return nil |
| 510 | } |
| 511 | |
| 512 | // Flush 刷新写入器 |
| 513 | func (w *JSONWriter) Flush() error { |