golang中讀取檔案的幾種方式
阿新 • • 發佈:2022-03-22
golang中的檔案的讀取很多是做配置檔案使用,還有是讀取影象作為file類,儲存至檔案系統中,下面分別說明
一.配置檔案讀取
type GlobalConf struct { Db structdef.DbConf `json:"db"` } //配置檔案中字母要小寫,結構體屬性首字母要大寫 type DbConf struct { UserName string `json:"username"` Password string `json:"password"` Host string `json:"host"` DataBase string `json:"database"` LogMode int `json:"logMode"` MaxOpenConn int `ymal:"maxopenconn"` MaxIdleConn int `ymal:"maxidleconn"` MaxLifetime int `ymal:"maxlifetime"` } var Config GlobalConf
1.Yaml檔案的讀取
配置檔名稱:config.yaml
db: # 資料庫配置(mysql),mysql服務部署 見部署手冊,或基於TDSQL/CDB搭建
username: "root" # 資料庫使用者名稱
password: "*******" # 資料庫密碼
host: "127.0.0.1:3306" # 資料庫連線地址
logmode: 4
maxopenconn: 50 # 連線池最大連線數
maxidleconn: 2 # 最大空閒連線
maxlifetime: 30 # 空閒連線的超時時間
配置檔案路徑:conf/config.yaml
依賴:使用Init函式進行封裝,依賴包為: "gopkg.in/yaml.v2"
1.讀取路徑,以專案的根目錄為參考:根目錄下的conf路徑下的config.yaml檔案,讀取路徑就為:conf/config.yaml
//從配置檔案中讀取所有的配置資訊 func Init() { err := GetYamlConfig() if err != nil { //使用預設配置檔案 } } func GetYamlConfig() error { file, err := ioutil.ReadFile("conf/config.yaml") //讀取的位置是從專案根目錄作為當前目錄 if err != nil { log.Logger.Errorf("config int fail %s", err.Error()) return err } err = yaml.Unmarshal(file, &Config) if err != nil { return err } log.Logger.Infof("config is %v", Config) return nil }
2.json檔案
配置檔名稱:config.json
配置檔案路徑:conf/config.json
{
"db": {
"username": "root",
"password": "molotest123",
"host": "127.0.0.1:3306",
"logmode": 4,
"maxopenconn": 50,
"maxidleconn": 2,
"maxlifetime": 30
}
}
程式實現:
func GetJsonConfig() error {
file, _ := os.Open("conf/config.json")
decoder := json.NewDecoder(file)
err := decoder.Decode(&Config)
if err != nil {
return err
}
log.Logger.Infof("config is %v", Config)
return nil
}
3.ini檔案的讀取
配置檔名稱:config.ini
所在路徑:conf/config.ini
檔案內容
[db]
username="root" # 資料庫使用者名稱
password="******" # 資料庫密碼
host="127.0.0.1:3306" # 資料庫連線地址
logmode= 4
maxopenconn= 50 # 連線池最大連線數
maxidleconn= 2 # 最大空閒連線
maxlifetime= 30 # 空閒連線的超時時間
引入的包為:github.com/go-ini/ini
程式碼實現:
err := ini.MapTo(&Config, "conf/config.ini") //配置使用指標的方式接收
if err != nil {
return err
}
log.Logger.Infof("ini read config is %v", Config)
return nil
}
二.檔案的操作
golang中檔案的操作使用系統自帶的工具
1.開啟本地檔案:
file, err := os.Open(localPic)
if err != nil {
logger.Error("open localPic fail:", err)
}
defer file.Close()
2.開啟/建立本地copy的目的檔案
fd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
if err != nil {
return resp, err
}