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.
Code
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: "[email protected]",
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
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.