github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/encoder.go (about)

     1  package jzon
     2  
     3  // Encoder is almost standard library compatible
     4  // The following standard methods are not implemented
     5  // - SetIndent
     6  type Encoder struct {
     7  	s   *Streamer
     8  	err error
     9  }
    10  
    11  // Release encoder, encoder should not be reused after call
    12  func (e *Encoder) Release() {
    13  	e.s.Release()
    14  	e.s = nil
    15  }
    16  
    17  func encodeInternal(s *Streamer, v interface{}) error {
    18  	if err := s.Value(v).Flush(); err != nil {
    19  		return err
    20  	}
    21  	_, err := s.writer.Write([]byte{'\n'})
    22  	if err != nil {
    23  		return err
    24  	}
    25  	s.Reset(s.writer)
    26  	return nil
    27  }
    28  
    29  // Encode writes the JSON encoding of v to the stream,
    30  // followed by a newline character.
    31  func (e *Encoder) Encode(v interface{}) error {
    32  	if e.err == nil {
    33  		e.err = encodeInternal(e.s, v)
    34  	}
    35  	return e.err
    36  }
    37  
    38  // SetEscapeHTML specifies whether problematic HTML characters
    39  // should be escaped inside JSON quoted strings.
    40  // The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e
    41  // to avoid certain safety problems that can arise when embedding JSON in HTML.
    42  //
    43  // In non-HTML settings where the escaping interferes with the readability
    44  // of the output, SetEscapeHTML(false) disables this behavior.
    45  func (e *Encoder) SetEscapeHTML(on bool) {
    46  	e.s.EscapeHTML(on)
    47  }
    48  
    49  // func (e *Encoder) SetIndent(prefix, indent string) {
    50  // 	e.s.SetIndent(prefix, indent)
    51  // }