github.com/newrelic/go-agent@v3.26.0+incompatible/internal/json_object_writer.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package internal
     5  
     6  import (
     7  	"bytes"
     8  
     9  	"github.com/newrelic/go-agent/internal/jsonx"
    10  )
    11  
    12  type jsonWriter interface {
    13  	WriteJSON(buf *bytes.Buffer)
    14  }
    15  
    16  type jsonFieldsWriter struct {
    17  	buf        *bytes.Buffer
    18  	needsComma bool
    19  }
    20  
    21  func (w *jsonFieldsWriter) addKey(key string) {
    22  	if w.needsComma {
    23  		w.buf.WriteByte(',')
    24  	} else {
    25  		w.needsComma = true
    26  	}
    27  	// defensively assume that the key needs escaping:
    28  	jsonx.AppendString(w.buf, key)
    29  	w.buf.WriteByte(':')
    30  }
    31  
    32  func (w *jsonFieldsWriter) stringField(key string, val string) {
    33  	w.addKey(key)
    34  	jsonx.AppendString(w.buf, val)
    35  }
    36  
    37  func (w *jsonFieldsWriter) intField(key string, val int64) {
    38  	w.addKey(key)
    39  	jsonx.AppendInt(w.buf, val)
    40  }
    41  
    42  func (w *jsonFieldsWriter) floatField(key string, val float64) {
    43  	w.addKey(key)
    44  	jsonx.AppendFloat(w.buf, val)
    45  }
    46  
    47  func (w *jsonFieldsWriter) boolField(key string, val bool) {
    48  	w.addKey(key)
    49  	if val {
    50  		w.buf.WriteString("true")
    51  	} else {
    52  		w.buf.WriteString("false")
    53  	}
    54  }
    55  
    56  func (w *jsonFieldsWriter) rawField(key string, val JSONString) {
    57  	w.addKey(key)
    58  	w.buf.WriteString(string(val))
    59  }
    60  
    61  func (w *jsonFieldsWriter) writerField(key string, val jsonWriter) {
    62  	w.addKey(key)
    63  	val.WriteJSON(w.buf)
    64  }