gorm/utils/utils.go

67 lines
1.3 KiB
Go
Raw Normal View History

2020-01-31 01:35:25 +03:00
package utils
import (
"database/sql/driver"
2020-01-31 01:35:25 +03:00
"fmt"
"reflect"
2020-01-31 01:35:25 +03:00
"regexp"
"runtime"
2020-05-14 07:19:12 +03:00
"strconv"
"strings"
2020-03-09 08:10:48 +03:00
"unicode"
2020-01-31 01:35:25 +03:00
)
2020-04-03 02:15:30 +03:00
var goSrcRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*.go`)
var goTestRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*test.go`)
2020-01-31 01:35:25 +03:00
func FileWithLineNum() string {
for i := 2; i < 15; i++ {
_, file, line, ok := runtime.Caller(i)
if ok && (!goSrcRegexp.MatchString(file) || goTestRegexp.MatchString(file)) {
return fmt.Sprintf("%v:%v", file, line)
}
}
return ""
}
2020-03-09 08:10:48 +03:00
func IsChar(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
func CheckTruth(val interface{}) bool {
if v, ok := val.(bool); ok {
return v
}
if v, ok := val.(string); ok {
v = strings.ToLower(v)
return v != "false"
}
return !reflect.ValueOf(val).IsZero()
}
2020-05-14 07:19:12 +03:00
func ToStringKey(values ...reflect.Value) string {
results := make([]string, len(values))
for idx, value := range values {
rv := reflect.Indirect(value).Interface()
if valuer, ok := rv.(driver.Valuer); ok {
rv, _ = valuer.Value()
}
2020-05-14 07:19:12 +03:00
switch v := rv.(type) {
case string:
results[idx] = v
case []byte:
results[idx] = string(v)
case uint:
results[idx] = strconv.FormatUint(uint64(v), 10)
default:
results[idx] = fmt.Sprint(v)
}
}
return strings.Join(results, "_")
}