github.com/amp-space/amp-sdk-go@v0.7.6/stdlib/utils/misc.go (about)

     1  package utils
     2  
     3  import (
     4  	"encoding/json"
     5  	"math/rand"
     6  	"strconv"
     7  )
     8  
     9  func RandomBytes(length int) []byte {
    10  	bs := make([]byte, length)
    11  	rand.Read(bs)
    12  	return bs
    13  }
    14  
    15  func RandomString(n int) string {
    16  	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    17  
    18  	s := make([]rune, n)
    19  	for i := range s {
    20  		s[i] = letters[rand.Intn(len(letters))]
    21  	}
    22  	return string(s)
    23  }
    24  
    25  func GetValue(x interface{}, keypath []string) (interface{}, bool) {
    26  	for i := 0; i < len(keypath); i++ {
    27  		if asMap, isMap := x.(map[string]interface{}); isMap {
    28  			var exists bool
    29  			x, exists = asMap[keypath[i]]
    30  			if !exists {
    31  				return nil, false
    32  			}
    33  
    34  		} else if asSlice, isSlice := x.([]interface{}); isSlice {
    35  			sliceIdx, err := strconv.ParseInt(keypath[i], 10, 64)
    36  			if err != nil {
    37  				return nil, false
    38  			} else if sliceIdx > int64(len(asSlice)-1) {
    39  				return nil, false
    40  			}
    41  			x = asSlice[sliceIdx]
    42  
    43  		} else {
    44  			return nil, false
    45  		}
    46  	}
    47  	return x, true
    48  }
    49  
    50  // @@TODO: everything about this is horrible
    51  func DeepCopyJSValue(val interface{}) interface{} {
    52  	bs, err := json.Marshal(val)
    53  	if err != nil {
    54  		panic(err)
    55  	}
    56  	var copied interface{}
    57  	err = json.Unmarshal(bs, &copied)
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  	return copied
    62  }
    63  
    64  func PrettyJSON(x interface{}) string {
    65  	j, _ := json.MarshalIndent(x, "", "    ")
    66  	return string(j)
    67  }