1 Star 0 Fork 0

tomatomeatman/GolangRepository

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
LocalUtil.go 3.04 KB
一键复制 编辑 原始数据 按行查看 历史
tomatomeatman 提交于 2025-04-15 23:44 +08:00 . 2
package wailsutil
import (
"os"
"path/filepath"
"regexp"
"strings"
"github.com/juju/fslock"
"gopkg.in/ini.v1"
)
/**
* 读取配置文件中指定块下的指定键
*/
func ReadConfig(file string, section string, key string) string {
cfg, err := ini.Load(file)
if err != nil {
clogger.Error("文件读取错误:" + err.Error())
os.Exit(1)
}
result := string(cfg.Section(section).Key(key).Value())
return replacePlaceholders(result, cfg)
}
/**
* 读取配置文件中指定块下的指定键
*/
func Read(cfg *ini.File, section string, key string) string {
if cfg == nil {
clogger.Error("传入参数cfg为空")
return ""
}
result := string(cfg.Section(section).Key(key).Value())
return replacePlaceholders(result, cfg)
}
/**
* 文件加锁
*/
func LockFile() bool {
CareteDir("./temp") // 创建文件夹
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fileName := dir + "/temp/App.lock"
file, er := os.Open(fileName)
defer func() { file.Close() }()
if er != nil && os.IsNotExist(er) {
file, _ = os.Create(fileName)
}
defer file.Close()
lock := fslock.New(fileName)
lockErr := lock.TryLock()
if lockErr == nil {
return true
}
if lockErr.Error() == "fslock is already locked" {
clogger.Error("文件已枷锁,程序可能设置了单例运行模式且正在运行中")
return false
}
clogger.Error("文件加锁失败异常:" + lockErr.Error())
return false
}
/**
* 创建文件夹
*/
func CareteDir(path string) {
exist, err := PathExists(path)
if err != nil {
clogger.Error("获取路径错误:" + err.Error())
}
if exist {
return
}
err = os.MkdirAll(path, os.ModePerm) // 创建文件夹
if err != nil {
clogger.Error("创建文件夹失败:" + err.Error())
return
}
}
/**
* 判断文件夹是否存在
*/
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// 获取当前执行程序目录
func GetCurrentDirectory() string {
//返回绝对路径 filepath.Dir(os.Args[0])去除最后一个元素的路径
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
clogger.Error(err.Error())
}
//将\替换成/
return strings.Replace(dir, "\\", "/", -1)
}
/**
* 替换占位符
* @param str
* @param cfg
* @return string
*/
func replacePlaceholders(str string, cfg *ini.File) string {
// 检查是否包含 ${} 字符
if !strings.Contains(str, "${") {
return str
}
// 使用正则表达式查找占位符
re := regexp.MustCompile(`\$\{([^}]+)\}`)
return re.ReplaceAllStringFunc(str, func(match string) string {
// 去掉 ${} 部分,获取占位符名称
placeholder := match[2 : len(match)-1]
// 查找占位符对应的值
sectionKey := strings.SplitN(placeholder, ".", 2)
if len(sectionKey) != 2 {
return match
}
section := sectionKey[0]
key := sectionKey[1]
value := cfg.Section(section).Key(key).String()
if value == "" {
// 如果没有找到对应的值,返回原始占位符
return match
}
return value
})
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tomatomeatman/golang-repository.git
git@gitee.com:tomatomeatman/golang-repository.git
tomatomeatman
golang-repository
GolangRepository
317a76404e4d

搜索帮助