1 Star 1 Fork 0

bon-ami/eztools

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cfg.go 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Tse 提交于 2022-01-25 10:32 +08:00 . FileWrite added
package eztools
import (
"encoding/xml"
"io/ioutil"
"os"
"path/filepath"
)
// FileWrite writes input bytes to file
func FileWrite(file string, bytes []byte, createIfNeeded bool) error {
if !createIfNeeded {
if _, err := os.Stat(file); err != nil {
return err
}
}
const PERMISSIONS = 0644
return ioutil.WriteFile(file, bytes, PERMISSIONS)
}
// XMLWrite writes input structure to file
// this reformats the file with indent provided
func XMLWrite(file string, data interface{}, createIfNeeded bool, indent string) error {
bytes, err := xml.MarshalIndent(data, "", indent)
if err != nil {
return err
}
var PREFIX = []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
return FileWrite(file, append(PREFIX, bytes...), createIfNeeded)
}
// XMLWriteNoCreate writes config file from input structure
// by a full path (with .xml extension)
// this reformats the file with indent provided
func XMLWriteNoCreate(file string, cfg interface{}, indent string) error {
return XMLWrite(file, cfg, false, indent)
}
// XMLRead reads file into input structure
func XMLRead(file string, data interface{}, _ bool) error {
if _, err := os.Stat(file); err != nil {
return err
}
bytes, err := ioutil.ReadFile(file)
if err != nil {
return err
}
return xml.Unmarshal(bytes, data)
}
// XMLsReadDefault reads a config file
func XMLsReadDefault(path, file string, cfg interface{},
createIfNeeded bool) (
pathFound string, err error) {
if len(path) > 0 {
err = XMLRead(path, cfg, createIfNeeded)
if err == nil {
return path, err
}
}
if len(file) < 1 {
return "", ErrNoValidResults
}
home, _ := os.UserHomeDir()
cfgPaths := [...]string{".", home}
for _, path1 := range cfgPaths {
pathFound = filepath.Join(path1, file+".xml")
err = XMLRead(pathFound, cfg, createIfNeeded)
if err == nil {
return
}
}
return "", ErrNoValidResults
}
// XMLsReadDefaultNoCreate reads config file into input structure from
// given path, or given file name (plus .xml) under current dir or home dir
// returns full file name with path
func XMLsReadDefaultNoCreate(path, file string, cfg interface{}) (string, error) {
return XMLsReadDefault(path, file, cfg, false)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/bon-ami/eztools.git
git@gitee.com:bon-ami/eztools.git
bon-ami
eztools
eztools
v2.1.1

搜索帮助