go-gallery/modules/utils/utils.go

85 lines
1.5 KiB
Go
Raw Normal View History

2018-04-17 10:04:36 +00:00
package utils
2018-04-18 06:16:29 +00:00
import (
2018-05-08 08:19:51 +00:00
"os"
"path"
2018-04-18 06:16:29 +00:00
"reflect"
"regexp"
2018-05-08 08:19:51 +00:00
"runtime"
"strings"
2018-04-18 06:16:29 +00:00
)
2018-04-17 10:04:36 +00:00
// ToMap struct to map[string]interface{}
func ToMap(ss interface{}) map[string]interface{} {
2018-04-24 09:49:58 +00:00
t := reflect.ValueOf(ss)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
2018-04-17 10:04:36 +00:00
smap := make(map[string]interface{})
2018-04-18 06:16:29 +00:00
mtag := regexp.MustCompile(`cc:\"(.+)\"`)
2018-04-17 10:04:36 +00:00
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
2018-04-18 06:16:29 +00:00
tag := string(t.Type().Field(i).Tag)
str := mtag.FindStringSubmatch(tag)
name := t.Type().Field(i).Name
if len(str) > 1 {
name = str[1]
}
if name != "-" {
smap[name] = f.Interface()
}
2018-04-17 10:04:36 +00:00
}
return smap
}
2018-05-08 08:19:51 +00:00
// ParsePath - parse file path to absPath
func ParsePath(dst string) string {
wd, err := os.Getwd()
if err != nil {
wd = ""
}
if []rune(dst)[0] == '~' {
home := UserHomeDir()
if len(home) > 0 {
dst = strings.Replace(dst, "~", home, -1)
}
}
if path.IsAbs(dst) {
dst = path.Clean(dst)
return dst
}
str := path.Join(wd, dst)
str = path.Clean(str)
return str
}
// UserHomeDir - get user home directory
func UserHomeDir() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
} else if runtime.GOOS == "plan9" {
env = "home"
}
return os.Getenv(env)
}
// CheckExists - check file exists
func CheckExists(filePath string, allowDir bool) bool {
filePath = ParsePath(filePath)
stat, err := os.Stat(filePath)
if err != nil && !os.IsExist(err) {
return false
}
if !allowDir && stat.IsDir() {
return false
}
return true
}