Redact Debug Output With GoStringer

Implement fmt.GoStringer so the %#v verb prints a redacted summary for credential-bearing types instead of leaking password fields into debug logs.

GoSecurity Boundaries

Code

snippet
package main

import "fmt"

type Credentials struct {
	Username string
	Password string
}

// GoStringer 控制 %#v 输出:敏感类型绝不打印原始字段
func (c Credentials) GoString() string {
	return fmt.Sprintf("credentials{user: %q, password: [redacted]}", c.Username)
}

func main() {
	creds := Credentials{Username: "deploy-bot", Password: "hunter2"}

	fmt.Printf("%#v
", creds)

	// %v 不会走 GoString:默认结构体打印仍含明文,别把 %v 的结果写进日志
	fmt.Println("plain %v still leaks:", fmt.Sprintf("%v", creds))

	// 拼进错误信息时用 %#v 才能保持脱敏
	err := fmt.Errorf("auth failed for %#v", creds)
	fmt.Println(err)
}

Following the data through the code

What actually works here is the functions GoString and main — everything else is wiring.

Watch out for

  • The import list holds no packages; the runtime supplies everything it needs.

Applying it

The signature this file is built around: func (c Credentials) GoString() string

Output lines are prefixed (plain), so the step behind every output line stays visible.

Statements that matter

return fmt.Sprintf("credentials{user: %q, password: [redacted]}", c.Username)
func main() {
	creds := Credentials{Username: "deploy-bot", Password: "hunter2"}
	fmt.Printf("%#v
", creds)
	// %v 不会走 GoString:默认结构体打印仍含明文,别把 %v 的结果写进日志
	fmt.Println("plain %v still leaks:", fmt.Sprintf("%v", creds))
	// 拼进错误信息时用 %#v 才能保持脱敏
	err := fmt.Errorf("auth failed for %#v", creds)
	fmt.Println(err)
}

Interactive Tools for This Topic

FAQ

What does Redact Debug Output With GoStringer print when run?
Invoke the file as-is — the `plain` prefixes identify which step printed each line.