123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package util
- import (
- "os"
- "reflect"
- "strconv"
- "time"
- )
- // IsNumber 判断一个值是否可转换为数值。不支持全角数值的判断。
- func IsNumber(val interface{}) bool {
- switch v := val.(type) {
- case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
- return true
- case []byte:
- _, err := strconv.ParseFloat(string(v), 32)
- return err == nil
- case string:
- _, err := strconv.ParseFloat(v, 32)
- return err == nil
- case []rune:
- _, err := strconv.ParseFloat(string(v), 32)
- return err == nil
- default:
- return false
- }
- }
- // IsNil 是否为 nil,有类型但无具体值的也将返回 true,
- // 当特定类型的变量,已经声明,但还未赋值时,也将返回 true
- func IsNil(val interface{}) bool {
- if nil == val {
- return true
- }
- v := reflect.ValueOf(val)
- k := v.Kind()
- return k >= reflect.Chan && k <= reflect.Slice && v.IsNil()
- }
- // Empty 是否为空,若是容器类型,长度为 0 也将返回 true,
- // 但是 []string{""}空数组里套一个空字符串,不会被判断为空。
- func IsEmpty(val interface{}) bool {
- if val == nil {
- return true
- }
- switch v := val.(type) {
- case bool:
- return !v
- case int:
- return 0 == v
- case int8:
- return 0 == v
- case int16:
- return 0 == v
- case int32:
- return 0 == v
- case int64:
- return 0 == v
- case uint:
- return 0 == v
- case uint8:
- return 0 == v
- case uint16:
- return 0 == v
- case uint32:
- return 0 == v
- case uint64:
- return 0 == v
- case string:
- return len(v) == 0
- case float32:
- return 0 == v
- case float64:
- return 0 == v
- case time.Time:
- return v.IsZero()
- case *time.Time:
- return v.IsZero()
- }
- // 符合 Nil 条件的,都为 Empty
- if IsNil(val) {
- return true
- }
- // 长度为 0 的数组也是 empty
- v := reflect.ValueOf(val)
- switch v.Kind() {
- case reflect.Slice, reflect.Map, reflect.Chan:
- return 0 == v.Len()
- }
- return false
- }
- // IsExistFile 判断文件或是文件夹是否存在
- func IsFileExist(filename string) bool {
- _, err := os.Stat(filename)
- return err == nil || os.IsExist(err)
- }
|