golang學(xué)習(xí)筆記(10)
2111
發(fā)布于 2021-08-30 · 3.7w瀏覽 5贊

這是一段讀取配置文件的代碼,可以從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",

}

2111
~
瀏覽 3.7w
5
相關(guān)推薦
最新評論
贊過的人 5
評論加載中...

暫無評論,快來評論吧!