2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Goでconfigファイルを読み込む

Posted at

必要なパッケージをインストール

パッケージのインストール
go get gopkg.in/ini.v1

config.iniファイルの例

config.ini
[db_setting]
host = mysql
user_name = root
password = password
db_name = development

実装

main.go
package main

import (
	"fmt"

	"gopkg.in/ini.v1"
)

// ConfigList 設定ファイルから取得したデータを保持する構造体
type ConfigList struct {
	Host     string
	UserName string
	Password string
	DBName   string
}

// Config 設定リスト保持変数
var Config ConfigList

// コンストラクタ
func init() {
	// ファイル読み込み
	cfg, err := ini.Load("config.ini")
	if err != nil {

	}

	// 変数に設定
	Config = ConfigList{
		Host:     cfg.Section("db_setting").Key("host").String(),
		UserName: cfg.Section("db_setting").Key("user_name").String(),
		Password: cfg.Section("db_setting").Key("password").String(),
		DBName:   cfg.Section("db_setting").Key("db_name").String(),
	}
}

func main() {
	// 以下の形でアクセスできる
	fmt.Println(Config.Host)
	fmt.Println(Config.UserName)
}

2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?