【golang程序包推荐分享】go-ini、viper、godoc
生活随笔
收集整理的這篇文章主要介紹了
【golang程序包推荐分享】go-ini、viper、godoc
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【golang程序包推薦&分享】go-ini、viper、godoc
- 一、go-ini
- 1.程序包簡介
- 2.下載安裝
- 3.簡單使用【截取自官網】
- 二、viper
- 1.程序包簡介
- 2.下載安裝
- 3.簡單使用
- 三、godoc
- 1.程序包簡介
- 2.下載安裝
- 3.簡單使用
一、go-ini
1.程序包簡介
ini 是常用的配置文件格式,而go-ini是 Go 語言中用于操作 ini 文件的第三方庫。
2.下載安裝
最低要求安裝 Go 語言版本為 1.6。
$ go get gopkg.in/ini.v1
3.簡單使用【截取自官網】
首先,我們需要在任意目錄創建兩個文件(my.ini 和 main.go),在這里我們選擇 /tmp/ini 目錄。
$ mkdir -p /tmp/ini
$ cd /tmp/ini
$ touch my.ini main.go
$ tree .
.
├── main.go
└── my.ini0 directories, 2 files
現在,我們編輯 my.ini 文件并輸入以下內容
# possible values : production, development
app_mode = development[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana[server]
# Protocol (http or https)
protocol = http# The http port to use
http_port = 9999# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
enforce_domain = true
很好,接下來我們需要編寫 main.go 文件來操作剛才創建的配置文件。
package mainimport ("fmt""os""gopkg.in/ini.v1"
)func main() {cfg, err := ini.Load("my.ini")if err != nil {fmt.Printf("Fail to read file: %v", err)os.Exit(1)}// 典型讀取操作,默認分區可以使用空字符串表示fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())// 我們可以做一些候選值限制的操作fmt.Println("Server Protocol:",cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))// 如果讀取的值不在候選列表內,則會回退使用提供的默認值fmt.Println("Email Protocol:",cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))// 試一試自動類型轉換fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999))fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false))// 差不多了,修改某個值然后進行保存cfg.Section("").Key("app_mode").SetValue("production")cfg.SaveTo("my.ini.local")
}
運行程序,我們可以看下以下輸出:
$ go run main.go
App Mode: development
Data Path: /home/git/grafana
Server Protocol: http
Email Protocol: smtp
Port Number: (int) 9999
Enforce Domain: (bool) true$ cat my.ini.local
# possible values : production, development
app_mode = production[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana
...
二、viper
1.程序包簡介
viper 是一個配置解決方案,擁有豐富的特性:
支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多種格式的配置文件;
可以設置監聽配置文件的修改,修改時自動加載新的配置;
從環境變量、命令行選項和io.Reader中讀取配置;
從遠程配置系統中讀取和監聽修改,如 etcd/Consul;
代碼邏輯中顯示設置鍵值。
2.下載安裝
$ go get github.com/spf13/viper
3.簡單使用
package mainimport ("fmt""log""github.com/spf13/viper"
)func init() {// viper.SetConfigName("config1") // 讀取yaml配置文件viper.SetConfigName("config") // 讀取json配置文件//viper.AddConfigPath("/etc/appname/") //設置配置文件的搜索目錄//viper.AddConfigPath("$HOME/.appname") // 設置配置文件的搜索目錄viper.AddConfigPath(".") // 設置配置文件和可執行二進制文件在用一個目錄if err := viper.ReadInConfig(); err != nil {if _, ok := err.(viper.ConfigFileNotFoundError); ok {// Config file not found; ignore error if desiredlog.Println("no such config file")} else {// Config file was found but another error was producedlog.Println("read config error")}log.Fatal(err) // 讀取配置文件失敗致命錯誤}
}func main() {fmt.Println("獲取配置文件的port", viper.GetInt("port"))fmt.Println("獲取配置文件的mysql.url", viper.GetString(`mysql.url`))fmt.Println("獲取配置文件的mysql.username", viper.GetString(`mysql.username`))fmt.Println("獲取配置文件的mysql.password", viper.GetString(`mysql.password`))fmt.Println("獲取配置文件的redis", viper.GetStringSlice("redis"))fmt.Println("獲取配置文件的smtp", viper.GetStringMap("smtp"))
}
三、godoc
1.程序包簡介
godoc是Go語言中一個可以自動生成 API 文檔的第三方庫。
2.下載安裝
$ git clone https://github.com/golang/tools $GOPATH/src/golang.org/x/tools
$ go build golang.org/x/tools
3.簡單使用
以筆者開發的simpleConfig_v1程序包為例,生成API文檔如下。
將項目simpleConfig_v1的simpleConfig_v1.go文件的main函數注釋掉,package改為package simpleConfig_v1,然后執行如下指令:
go install
go doc
godoc -url="pkg/github.com/user/simpleConfig_v1" > API.html
便會在當前目錄下生成API.html文件:
總結
以上是生活随笔為你收集整理的【golang程序包推荐分享】go-ini、viper、godoc的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Golang的监听读取配置文件的程序
- 下一篇: 基于Golang的对象序列化的程序包开发