EncodeDocTo streams a NetworkTrafficDoc to w in the specified format. - For JSON: writes a single compact JSON object followed by '\n' (NDJSON). - For YAML: writes a single YAML document (no trailing document separator); caller is responsible for writing the `---\n` separator between documents. Str
(w io.Writer, format Format, doc *NetworkTrafficDoc)
| 177 | // |
| 178 | // Streaming avoids a full []byte allocation for each document. |
| 179 | func EncodeDocTo(w io.Writer, format Format, doc *NetworkTrafficDoc) error { |
| 180 | switch format { |
| 181 | case FormatJSON: |
| 182 | jsonDoc, err := DocToJSON(doc) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | // json.Encoder.Encode appends a trailing '\n', which is NDJSON-compatible. |
| 187 | return json.NewEncoder(w).Encode(jsonDoc) |
| 188 | default: |
| 189 | enc := yamlLib.NewEncoder(w) |
| 190 | if err := enc.Encode(doc); err != nil { |
| 191 | _ = enc.Close() |
| 192 | return err |
| 193 | } |
| 194 | return enc.Close() |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | // MarshalGeneric serializes any value to bytes in the specified format. |
| 199 | func MarshalGeneric(format Format, v any) ([]byte, error) { |