← 中文资源

简体中文版本

json:"-" 阻止密钥进入输出

给敏感字段标注 json:"-":密码哈希与会话令牌不会进入编码输出,日志与响应没有泄露面;字段在进程内照常可用,拦截只发生在编码边界。

阅读英文原文

实现说明

json:“-” 阻止密钥进入输出的核心是函数 main。 err 在 1 处被测试,非 nil 就以 panic(err) 中止运行。

使用要点

  • 示例不返回错误——任何非 nil 的 err 都会让运行立即结束。
  • 每一步打印都带着自己的标签:internal still has hash:。

常见问题

调用失败时会发生什么?

这里没有错误返回值:非 nil 的 err 会立即走到 panic(err)。

运行「json:“-” 阻止密钥进入输出」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 internal still has hash: 这类标签。

核心语句

if err != nil {
	panic(err)
}

代码示例

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 != "")
}