I typically perform comprehensive checks on various data structures (such as struct, array, slice, map, pointer, etc.) but prefer to avoid excessive if statements for object validation.
Consequently, I developed a utility package for object validation to streamline this process, leveraging the capabilities of the Go reflection package.
package check
import (
"reflect"
)
func IsEmpty(obj interface{}) bool {
if obj == nil {
return true
}
objValue := reflect.ValueOf(obj)
switch objValue.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
return objValue.Len() == 0
case reflect.Ptr:
if objValue.IsNil() {
return true
}
ref := objValue.Elem().Interface()
return IsEmpty(ref)
default:
zero := reflect.Zero(objValue.Type())
return reflect.DeepEqual(obj, zero.Interface())
}
}
func IsEmptyOrWhiteSpace(str string) bool {
if IsEmpty(str) || len(strings.TrimSpace(str)) == 0 {
return true
}
return false
}
I got inspired from https://github.com/stretchr/testify