github.com/qiwihui/DBShield@v0.0.0-20171107092910-fb8553bed8ef/dbshield/db/utils.go (about) 1 package db 2 3 import ( 4 "errors" 5 "math/rand" 6 "reflect" 7 "time" 8 ) 9 10 //Contains check if target contains obj 11 func Contains(target interface{}, obj interface{}) (bool, error) { 12 targetValue := reflect.ValueOf(target) 13 switch reflect.TypeOf(target).Kind() { 14 case reflect.Slice, reflect.Array: 15 for i := 0; i < targetValue.Len(); i++ { 16 if targetValue.Index(i).Interface() == obj { 17 return true, nil 18 } 19 } 20 case reflect.Map: 21 if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() { 22 return true, nil 23 } 24 } 25 return false, errors.New("not in array") 26 } 27 28 //SContains string array contains 29 func SContains(target []string, obj string) (bool, error) { 30 for _, t := range target { 31 if t == obj { 32 return true, nil 33 } 34 } 35 return false, errors.New("not in array") 36 } 37 38 // RandString generate a random string of a fixed length 39 // https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang 40 func RandString(n int) string { 41 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 42 const ( 43 letterIdxBits = 6 // 6 bits to represent a letter index 44 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits 45 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits 46 ) 47 var src = rand.NewSource(time.Now().UnixNano()) 48 b := make([]byte, n) 49 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! 50 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { 51 if remain == 0 { 52 cache, remain = src.Int63(), letterIdxMax 53 } 54 if idx := int(cache & letterIdxMask); idx < len(letterBytes) { 55 b[i] = letterBytes[idx] 56 i-- 57 } 58 cache >>= letterIdxBits 59 remain-- 60 } 61 return string(b) 62 }