使用magiconair操作properties

读取,写入properties

package main

import (
	"flag"
	"fmt"
	"github.com/magiconair/properties"
	"log"
	"os"
	"time"
)

func main() {
	// 读取一个properties文件
	p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8)

	// 或者多去多个properties文件
	p = properties.MustLoadFiles([]string{
		"${HOME}/config.properties",
		"${HOME}/config-${USER}.properties",
	}, properties.UTF8, true)

	// 或者读取一个map
	p = properties.LoadMap(map[string]string{"key": "value", "abc": "def"})

	// 或者读取properties字符串
	p = properties.MustLoadString("key=value\nabc=def")

	// 或者从url中读取
	p = properties.MustLoadURL("http://host/path")

	// 或者读取多个url
	p = properties.MustLoadURLs([]string{
		"http://host/config",
		"http://host/config-${USER}",
	}, true)

	// 或者通过flag读取控制台
	p.MustFlag(flag.CommandLine)

	// 使用getter根据key获取对应的value,并且可以设置默认值
	host := p.MustGetString("host")
	port := p.GetInt("port", 8080)
	fmt.Println(host, port)

	// 通过Decode解析为struct结构体
	type Config struct {
		Host    string        `properties:"host"`              // 对应properties配置文件key为hsot
		Port    int           `properties:"port,default=9000"` // 可以设置默认值
		Accept  []string      `properties:"accept,default=image/png;image;gif"`
		Timeout time.Duration `properties:"timeout,default=5s"`
	}
	var cfg Config
	if err := p.Decode(&cfg); err != nil {
		log.Fatal(err)
	}

	// 将properties写入到指定的writer中,通常是文件
	// 第一个参数为文件路径,第二个参数为只写模式打开,第三个参数为权限为拥有该文件创建用户的权限
	write, err := os.OpenFile("${HOME}/config.properties", os.O_WRONLY, os.ModeSetuid)
	if err != nil {}

	p.Write(write, properties.UTF8) // 写入配置文件
}

最后更新于