Golang Snippets

2019-06-22

After

Get the part of a string after the last occurence of value

func after(value string, a string) string {
    // Get substring after a string.
    pos := strings.LastIndex(value, a)
    if pos == -1 {
       return ""
    }
    adjustedPos := pos + len(a)
    if adjustedPos >= len(value) {
       return ""
    }
    return value[adjustedPos:]
}

File Exists

func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}

Random Int

// Don't forget to seed rand!
// Best used in init so it only happens once.
func init() {
    rand.Seed(time.Now().UTC().UnixNano()) 
}

func random(min int, max int) int {
    return rand.Intn(max-min) + min
}

arr := []byte{'a', 'b', 'c'}

val := random(0, len(arr)-1)

Random String

A good way to generate a random string.

// Don't forget to seed rand!
// Best used in init so it only happens once.
func init() {
    rand.Seed(time.Now().UTC().UnixNano()) 
}

letterRunes := []rune("123abcdefgHIJKLMNOPQRSTUVWXYZ")

func randomString(min int, max int, letterRunes []rune) string {
    s1 := rand.NewSource(time.Now().UnixNano())
    r1 := rand.New(s1)

    n := r1.Intn(max-min) + min

    b := make([]rune, n)
    for i := range b {
        b[i] = letterRunes[rand.Intn(len(letterRunes))]
    }
    return string(b)
}