Files
BitSrunLoginGo/Util/file.go
Mmx f0c3df85da fix:修复bug若干
1、修复日志不追加的问题
2、修复未初始化时Demo mode读取panic问题
3、修复重构时文件名也被替换的问题
4、修复file包逻辑漏洞
5、log输出文件名新增时间戳
2021-05-05 11:19:13 +08:00

70 lines
1.3 KiB
Go

package Util
import (
"bufio"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
type file struct{}
var File file
func (*file) Exists(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func (a *file) Read(path string) ([]byte, error) {
return ioutil.ReadFile(a.GetRootPath() + path)
}
func (a *file) ReadJson(path string, receiver interface{}) error {
data, err := a.Read(path)
if err != nil {
return err
}
return json.Unmarshal(data, receiver)
}
func (a *file) Write(path string, data []byte) error {
return ioutil.WriteFile(a.GetRootPath()+path, data, 700)
}
func (a *file) WriteJson(path string, receiver interface{}) error {
data, err := json.MarshalIndent(receiver, "", " ")
if err != nil {
return err
}
return a.Write(path, data)
}
func (*file) GetRootPath() string {
t, err := os.Executable()
if err != nil {
ErrHandler(err)
}
return filepath.Dir(t) + "/"
}
func (a *file) Add(path string, c string) error {
file, err := os.OpenFile(a.GetRootPath()+path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 700)
defer file.Close()
if err != nil {
return err
}
w := bufio.NewWriter(file)
if _, err = w.WriteString(c + "\n"); err != nil {
return err
}
return w.Flush()
}