json_object_writer.go 1.2 KB

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