這是一段讀取配置文件的代碼,可以從json格式的配置文件里讀取相關(guān)數(shù)據(jù)
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
type Config struct {
Host string
User string
Pass string
}
func getConf() Config {
file, _ := os.Open("golang.conf")
defer file.Close()
decoder := json.NewDecoder(file)
conf := Config{}
err := decoder.Decode(&conf)
chkErr(err)
return conf
}
func chkErr(err error) {
if err != nil {
fmt.Println(err)
}
}
func main() {
conf := getConf()
fmt.Printf("host is: %v\n", conf.Host)
fmt.Printf("user name is: %v\n, conf.User)
fmt.Printf("password is: %v\n", conf.Pass)
}
golang.conf
{
"Host":"192.168.0.3",
"User":"root",
"Pass":"root",
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者





暫無評論,快來評論吧!