Skip to content
Go: Quote diagnostic values without embedding raw newlines

Go: Quote diagnostic values without embedding raw newlines

November 14, 2026

A diagnostic value containing a newline can make one event look like two lines. strconv.AppendQuote appends a Go string literal to a byte slice, making control characters visible while retaining a form that Unquote can decode.

Set up

Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as go-strconv-appendquote-diagnostic-values.go:

package main

import (
	"bytes"
	"fmt"
	"strconv"
)

func main() {
	for _, value := range []string{"plain", "first\nsecond", "tab\tquote\"", ""} {
		line := []byte("value=")
		line = strconv.AppendQuote(line, value)
		if bytes.ContainsRune(line, '\n') {
			panic("raw newline")
		}
		decoded, err := strconv.Unquote(string(line[len("value="):]))
		if err != nil || decoded != value {
			panic("round trip")
		}
		fmt.Println(string(line))
	}
}

Run:

go run go-strconv-appendquote-diagnostic-values.go

Observed output:

value="plain"
value="first\nsecond"
value="tab\tquote\""
value=""

Read the result

The slice already contains the field label. Assigning the returned slice preserves its updated length and any new backing array allocated during append. The example checks that the resulting diagnostic text has no raw newline and that decoding recovers each original value.

The output keeps the distinction between an empty string and a missing field because even the empty value has quotation marks.

Apply it carefully

Go string-literal syntax is not a general-purpose escaping format. Use the destination’s encoder for JSON or HTML, parameter binding for SQL, and argument lists for process execution. Quoting is also not redaction: credentials remain present in a reversible form. It does not impose a length limit or prevent all misleading visual text. Apply a size policy and remove secrets before formatting diagnostics. The test uses fixed in-memory values and writes no logs or files beyond standard output.

See the Go standard-library reference.

Clean up

Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.

rm -- go-strconv-appendquote-diagnostic-values.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on