Golang 读取 YAML 配置文件
1. 从配置文件中获取
- ./config/query-ip.yaml
influxdb:
server: <Your_Influxdb_Host>
port: 8086
- 代表示例
从配置文件中读取 influxdb 的 IP 和端口,然后将访问日志写入 DB
func initConfig() {
viper.SetConfigName("query-ip") // YAML 文件名 (不带后缀)
viper.AddConfigPath("./conf/") //添加配置文件所在的路径
// viper.SetConfigType("yaml") //设置配置文件类型
err3 := viper.ReadInConfig()
if err3 != nil {
fmt.Printf("config file error: %s\n", err3)
os.Exit(1)
}
influxdbServer := viper.Get("influxdb.server")
influxdbPort := viper.Get("influxdb.port")
writeInfludbURL = fmt.Sprintf("http://%s:%d/write?db=<your_database>", influxdbServer, influxdbPort)
}
2. 从 HTTP Response 中获取 YAML
解析 cURL 命令获取本机外网 IP 中返回的 YAML 格式数据。
# dhcp.cn/?ip=134.175.159.160
IP: 134.175.159.160
Address:
Country: 中国
Province: 广东省
City: 广州市
ISP: 电信
代码示例
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"strconv"
"strings"
"github.com/spf13/viper"
)
func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
clientIP := fmt.Sprintf("%s", req.Header.Get("X-Real-IP"))
queryURL := fmt.Sprintf("http://api.dhcp.cn/?ip=%s", clientIP)
responseClient, errClient := http.Get(queryURL) // 获取外网 IP
if errClient != nil {
fmt.Printf("获取外网 IP 失败,请检查网络\n")
panic(errClient)
}
// 程序在使用完 response 后必须关闭 response 的主体。
defer responseClient.Body.Close()
IPBody, _ := ioutil.ReadAll(responseClient.Body)
fmt.Fprintf(w, "%s", string(IPBody))
// 从 []byte 中解析 YAML
viper.SetConfigType("yaml")
viper.ReadConfig(bytes.NewBuffer(IPBody))
IP := fmt.Sprintf("%s", viper.Get("IP"))
Country := fmt.Sprintf("%s", viper.Get("Address.Country"))
Province := fmt.Sprintf("%s", viper.Get("Address.Province"))
City := fmt.Sprintf("%s", viper.Get("Address.City"))
ISP := fmt.Sprintf("%s", viper.Get("ISP"))
}
reference
- [1] viper. Reading Config from io.Reader
- [2] 起风了. 使用 go 读取配置文件
Copyright © YAML在线编辑器