iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 8
0
Modern Web

遺留系統重構 - 從 MEAN Stack 轉移到 go-vue-postgresql系列 第 8

Day 8 : 設定 - 讀取設定檔

在 Gamilms 裡會在 /config/system_config.json 中讀取全域性的設定,
比如 oAuth 用的 key 或是資料庫的連線字串等等...

在 Golang 裡讀取JSON格式的設定檔

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type webConfig struct {
	Driver string `json:"driver"`
	DBName string `json:"dbname"`
	User   string `json:"user"`
}

// WebConfig is content of webconfig.json
var WebConfig webConfig

func main() {
	jsonFile, err := os.Open("webconfig.json")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Successfully Opened webconfig.json")
	defer jsonFile.Close()

	byteValue, _ := ioutil.ReadAll(jsonFile)

	json.Unmarshal(byteValue, &WebConfig)

	fmt.Println("Driver: " + WebConfig.Driver)
	fmt.Println("DBName: " + WebConfig.DBName)
	fmt.Println("User: " + WebConfig.User)
}

用 os.Open 開啟檔案,
用 ioutil.ReadAll 讀取檔案內容,
用 json.Unmarshal 將檔案內容轉成定義的物件,並賦予變數 WebConfig 相對應的值
接著就可以讓其他模組透過 WebConfig 取用設定了


上一篇
Day 7 : 目標 - 最後的約束之地
下一篇
Day 9 : 線索 - 沿路的小餅乾 cookie
系列文
遺留系統重構 - 從 MEAN Stack 轉移到 go-vue-postgresql30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言