Encode writes the JSON encoding of v to the stream, with insignificant space characters elided, followed by a newline character. See the documentation for [Marshal] for details about the conversion of Go values to JSON.
(v any)
| 199 | // See the documentation for [Marshal] for details about the |
| 200 | // conversion of Go values to JSON. |
| 201 | func (enc *Encoder) Encode(v any) error { |
| 202 | if enc.err != nil { |
| 203 | return enc.err |
| 204 | } |
| 205 | |
| 206 | e := newEncodeState() |
| 207 | defer encodeStatePool.Put(e) |
| 208 | |
| 209 | err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML}) |
| 210 | if err != nil { |
| 211 | return err |
| 212 | } |
| 213 | |
| 214 | // Terminate each value with a newline. |
| 215 | // This makes the output look a little nicer |
| 216 | // when debugging, and some kind of space |
| 217 | // is required if the encoded value was a number, |
| 218 | // so that the reader knows there aren't more |
| 219 | // digits coming. |
| 220 | e.WriteByte('\n') |
| 221 | |
| 222 | b := e.Bytes() |
| 223 | if enc.indentPrefix != "" || enc.indentValue != "" { |
| 224 | enc.indentBuf, err = appendIndent(enc.indentBuf[:0], b, enc.indentPrefix, enc.indentValue) |
| 225 | if err != nil { |
| 226 | return err |
| 227 | } |
| 228 | b = enc.indentBuf |
| 229 | } |
| 230 | if _, err = enc.w.Write(b); err != nil { |
| 231 | enc.err = err |
| 232 | } |
| 233 | return err |
| 234 | } |
| 235 | |
| 236 | // SetIndent instructs the encoder to format each subsequent encoded |
| 237 | // value as if indented by the package-level function Indent(dst, src, prefix, indent). |