QuoteToASCII Printable Encoding

Escape arbitrary strings into safe ASCII literals with strconv.Quote and QuoteToASCII, keeping control bytes and non-ASCII visible in logs.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Quote:Go 字符串字面量转义,控制字符变为可见序列
	fmt.Println(strconv.Quote("line1\nline2"))

	// both functions produce printable, safe encoding for logs

	// QuoteToASCII:进一步把所有非 ASCII 转成 \u 转义,输出纯 ASCII
	fmt.Println(strconv.QuoteToASCII("café ☕"))

	// 不可打印字节以 \x 十六进制呈现
	fmt.Println(strconv.QuoteToASCII("\x00\x07\xff"))

	// Unquote 逆向还原:转义串回到原始字符串
	decoded, err := strconv.Unquote(strconv.Quote("line1\nline2"))
	fmt.Println(decoded, err)

	// ParseQuotedString 场景:Unquote 拒绝非引号包裹的输入
	_, err = strconv.Unquote("plain-token")
	fmt.Println("unquote bare token err:", err)
}

How it works

QuoteToASCII Printable Encoding reduces to the function main.

Caveats

  • It carries everything it needs in the file — no import reaches past the runtime.

Using it

Look for the unquote bare token err: prefixes when the file runs; they tie each line to its step.

Key statements

decoded, err := strconv.Unquote(strconv.Quote("line1\nline2"))

Interactive Tools for This Topic

FAQ

What does QuoteToASCII Printable Encoding print when run?
No setup needed: run the file and look for labeled lines like `unquote bare token err:` in the output.