Keep Secret Fields Out Of JSON Encoding

Mark fields with json:"-" so passwords and session tokens never enter encoded output, while staying fully usable inside the process.

GoSecurity Boundaries

Code

gosnippet
32 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Account struct {
	Email         string `json:"email"`
	DisplayName   string `json:"display_name"`
	PasswordHash  string `json:"-"`
	SessionCookie string `json:"-"`
}

func main() {
	account := Account{
		Email:         "ada@example.com",
		DisplayName:   "Ada",
		PasswordHash:  "$2a$10$N9qo8uLOickgx2ZMRZoMye",
		SessionCookie: "sid=8f3ac",
	}

	// json:"-" 让字段彻底不进入编码输出:日志/响应里没有密钥可泄露
	encoded, err := json.Marshal(account)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(encoded))

	// 字段仍在内存结构里,程序内部照常使用
	fmt.Println("internal still has hash:", account.PasswordHash != "")
}

What the file does

Keep Secret Fields Out Of JSON Encoding reduces to the function main.

Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).

What to watch for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Using it

The demo output is labeled (internal still has hash:), so every line in the printed output names the step that produced it.

Key statements

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does Keep Secret Fields Out Of JSON Encoding print when run?
Running the file directly is enough — expect labeled output lines such as `internal still has hash:`.