golang 讀取設定檔

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

unix 風格的設定檔


[default]path= c:/goversion = 1.44 [test]num =666something  = wrong  #注釋1#fdfdfd = fdfdfd    注釋整行refer= refer       //注釋3


config.go 

package confimport ("bufio""io""os""strings")const middle = "========="type Config struct {Mymap  map[string]stringstrcet string}func (c *Config) InitConfig(path string) {c.Mymap = make(map[string]string)f, err := os.Open(path)if err != nil {panic(err)}defer f.Close()r := bufio.NewReader(f)for {b, _, err := r.ReadLine()if err != nil {if err == io.EOF {break}panic(err)}s := strings.TrimSpace(string(b))//fmt.Println(s)if strings.Index(s, "#") == 0 {continue}n1 := strings.Index(s, "[")n2 := strings.LastIndex(s, "]")if n1 > -1 && n2 > -1 && n2 > n1+1 {c.strcet = strings.TrimSpace(s[n1+1 : n2])continue}if len(c.strcet) == 0 {continue}index := strings.Index(s, "=")if index < 0 {continue}frist := strings.TrimSpace(s[:index])if len(frist) == 0 {continue}second := strings.TrimSpace(s[index+1:])pos := strings.Index(second, "\t#")if pos > -1 {second = second[0:pos]}pos = strings.Index(second, " #")if pos > -1 {second = second[0:pos]}pos = strings.Index(second, "\t//")if pos > -1 {second = second[0:pos]}pos = strings.Index(second, " //")if pos > -1 {second = second[0:pos]}if len(second) == 0 {continue}key := c.strcet + middle + fristc.Mymap[key] = strings.TrimSpace(second)}}func (c Config) Read(node, key string) string {key = node + middle + keyv, found := c.Mymap[key]if !found {return ""}return v}

main.go


package mainimport ("conf""fmt")func main() {myConfig := new(cf.Config)myConfig.InitConfig("c:/config.txt")fmt.Println(myConfig.Read("default", "path"))fmt.Printf("%v", myConfig.Mymap)}



result:

c:/gomap[default=========path:c:/go default=========version:1.44 test=========num:666 test=========something:wrong test=========refer:refer]



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.