3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Goの備忘録】設定ファイルを用いて環境変数を外出ししたい

Last updated at Posted at 2025-04-24

前提

SQLiteを用いたTODOアプリを作成する過程で環境変数の設定方法を新しく学んだので、自分の備忘録として記載しています。

行うこと

設定ファイルを用いて環境変数を外出しする。

手順

1.config.goを作成する

configディレクトリ配下にconfig.goを作成します。

2.設定項目を管理する構造体と各設定項目のフィールドを定義する

各設定項目を管理する構造体とフィールドを定義します。
今回はサーバとDBの設定項目として以下を定義します。

  • Port:サーバのポート番号
  • SQLDriver:使用するドライバーの名前
  • DBName:使用するデータベースの名前
  • LogFile:ログを出力するファイル名

image.png

3.構造体をグローバルに宣言する

2.で定義した構造体を外部から呼び出せるようにグローバルで宣言します。

image.png

4.iniファイルを作成する

config.iniという設定ファイルを作成します。
外出ししたい設定項目はconfig.iniファイル内に記載します。

image.png

5.設定項目を読み込む関数を作成する

以下のように、config.go内で、config.iniに記載した各設定項目を読み込む関数を作成します。

func LoadConfig() {
	cfg, err := ini.Load("config.ini")
	if err != nil {
		log.Fatalln(err)
	}
	Config = ConfigList{
		Port:      cfg.Section("web").Key("Port").MustString("8080"),
		SLQDriver: cfg.Section("db").Key("driver").String(),
		DBName:    cfg.Section("db").Key("name").String(),
		LogFile:   cfg.Section("web").Key("logfile").String(),
	}
}

6.コンストラクタで5.で作成した関数を実行するように設定する

config.go内にinit関数を作成し、その中で5.で作成した関数を実行します。
これにより、main関数が実行される前に各設定項目を初期化することができます。

image.png

確認

main関数で各設定項目を表示してみます。

image.png

※補足

各設定項目をログファイルに出力する方法

utils配下にlogging.goというファイルを作成し、その中にログファイルの出力先やフォーマットを定義します。

func LoggingSettings(logFile string) {
	logfile, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) // 適当な権限を与えて読み込み
	if err != nil {
		log.Fatalln(err)
	}
	multiLogFile := io.MultiWriter(os.Stdout, logfile) // 出力先を標準出力とログファイルに指定
	log.SetFlags(log.Ldate|log.Ltime|log.Lshortfile) // ログのフォーマットを指定
	log.SetOutput(multiLogFile)
}

image.png

以下のように指定したフォーマットで標準出力にログが出力されます。

image.png

同様のフォーマットでログファイルにもログが出力されます。

image.png

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?