github.com/blend/go-sdk@v1.20220411.3/validate/util.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package validate 9 10 import ( 11 "reflect" 12 13 "github.com/blend/go-sdk/ex" 14 ) 15 16 // Errors 17 const ( 18 ErrNonLengthType ex.Class = "instance is a non-length type" 19 ) 20 21 // GetLength returns the length of an object or an error if it's not a thing that can have a length. 22 func GetLength(obj interface{}) (int, error) { 23 objValue := reflect.ValueOf(obj) 24 switch objValue.Kind() { 25 case reflect.Map, reflect.Slice, reflect.Chan, reflect.String: 26 { 27 if obj == nil { 28 return 0, nil 29 } else if obj == "" { 30 return 0, nil 31 } 32 if objValue.IsValid() { 33 return objValue.Len(), nil 34 } 35 return 0, nil 36 } 37 } 38 return 0, ErrNonLengthType 39 } 40 41 // IsNil returns if an object is nil or is a typed pointer to nil. 42 func IsNil(obj interface{}) bool { 43 if obj == nil { 44 return true 45 } 46 value := reflect.ValueOf(obj) 47 kind := value.Kind() 48 return kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() 49 }