FILE / Unmei/Backend
utils/utils.go
Исходный файл и его история в репозитории.
73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"reflect"
|
|
"strings"
|
|
)
|
|
|
|
func StringOrDefault(a, b string) string {
|
|
if len(a) == 0 {
|
|
return b
|
|
}
|
|
return a
|
|
}
|
|
|
|
func GetStructForDatabase(s interface{}) []string {
|
|
out := make([]string, 0)
|
|
el := reflect.ValueOf(s).Elem()
|
|
for i := 0; i < el.NumField(); i++ {
|
|
t := el.Type().Field(i)
|
|
tag := t.Tag
|
|
db := tag.Get("db")
|
|
if len(db) == 0 {
|
|
out = append(out, strings.ToLower(t.Name))
|
|
} else {
|
|
out = append(out, db)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func GetNamedForDatabase(s interface{}) []string {
|
|
out := make([]string, 0)
|
|
el := reflect.ValueOf(s).Elem()
|
|
for i := 0; i < el.NumField(); i++ {
|
|
t := el.Type().Field(i)
|
|
tag := t.Tag
|
|
db := tag.Get("db")
|
|
if len(db) == 0 {
|
|
out = append(out, ":"+strings.ToLower(t.Name))
|
|
} else {
|
|
out = append(out, ":"+db)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func GetStructAndNamedForDatabase(s interface{}) [][]string {
|
|
out := make([][]string, 0)
|
|
el := reflect.ValueOf(s).Elem()
|
|
for i := 0; i < el.NumField(); i++ {
|
|
t := el.Type().Field(i)
|
|
tag := t.Tag
|
|
ignore := tag.Get("ignore")
|
|
if ignore != "1" {
|
|
db := tag.Get("db")
|
|
if len(db) == 0 {
|
|
out = append(out, []string{strings.ToLower(t.Name), ":" + strings.ToLower(t.Name)})
|
|
} else {
|
|
out = append(out, []string{db, ":" + db})
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func MD5(s string) string {
|
|
hash := md5.New()
|
|
hash.Write([]byte(s))
|
|
return hex.EncodeToString(hash.Sum(nil))
|
|
}
|