golang web框架 配置檔案讀取 借鑑 beego
阿新 • • 發佈:2018-12-22
package gobbs import ( "encoding/xml" "io/ioutil" "log" "os" "path/filepath" "github.com/liangguangchuan/gobbs/lib" ) var ( //基礎配置檔案 BConf *Conf //專案訪問路徑 AppPath string //執行模式 dev prod RunMode string ) type Conf struct { Host string `xml:"server_host"` Port int64 `xml:"server_port"` AppName string `xml:"app_name"` RunMode string `xml:"run_mode"` } func init() { //建立 Conf BConf = newConf() var err error //獲取當前執行的 路徑 如果獲取失敗丟擲錯誤 if AppPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil { panic(err) } //獲取工作目錄 workPath, err := os.Getwd() if err != nil { panic(err) } //拼接 conf 路徑 confPath := filepath.Join(workPath, "conf", "conf.xml") //如果專案目錄拼接conf/conf.xml 不存在對應檔案 if !lib.FileExists(confPath) { confPath = filepath.Join(AppPath, "conf", "conf.xml") // 根據執行檔案目錄拼接conf/conf.xml 不存在對應檔案 if !lib.FileExists(confPath) { return } } //讀取檔案並賦值 conf if err = parseConfig(confPath); err != nil { panic(nil) } //輸出 最終構造體值 log.Fatal(BConf) } func newConf() *Conf { return &Conf{ Host: "127.0.0.1", Port: 8080, AppName: "xiaochuan", RunMode: DEV, } } //解析 conf.xml func parseConfig(confPath string) error { fileData, err := ioutil.ReadFile(confPath) if err != nil { return err } err = xml.Unmarshal(fileData, BConf) return err }