LoginSignup
0
1

More than 1 year has passed since last update.

Golang-構造体にあるパスワードなどのセキュリティ情報をログに出力しないようにする方法

Last updated at Posted at 2022-03-01

構造体をログに出力する際に、パスワードとかのようなセキュリティ情報を出力したくない場合は、方法の一つは 構造体の埋め込み(Embedded) 特性を利用することです。

構造体の埋め込みの形は、次のような形になります。

type 埋め込み構造体名 struct {
	フィールド名 型名
	フィールド名 型名
}

type 構造体名 struct {
	埋め込み構造体名
	フィールド名 型名
}

以下のような例で説明しますと、

RequestSanitized.PasswordRequest.Password を上書きすることになります。

Password を出力したくなければ、あえてRequestSanitized.Password を空値にすれば良いです。

type Request struct {
	Name   string      `json:"user"`
	Password string `json:"password"`
}

type RequestSanitized struct {
	Request
	Password   string `json:"password"`
}

以下、完全なる例です。

package main

import (
	"encoding/json"
	"fmt"

)

type Request struct {
	Name   string      `json:"user"`
	Password string `json:"password"`
}

type RequestSanitized struct {
	Request
	Password   string `json:"password"`
}

func main() {
	request := Request{Name: "wen", Password: "123"}
	requestSanitized := &RequestSanitized{
		Request: request,
	}

	requestSanitizedJson, _ := json.Marshal(requestSanitized)

	fmt.Println(string(requestSanitizedJson)) // {"user":"wen","password":""}
}

Go Playground デモ

元記事

Golang-構造体にあるパスワードなどのセキュリティ情報をログに出力しないようにする方法

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1