In this article, we will see how to write a Go program that generates random strings with different character sets using a function called randomHash.

First, we need to import the following packages

  • The fmt package is used for formatted I/O operations
  • math/rand is used for generating random numbers
  • strings is used for string manipulation
  • time is used for seeding the random number generator.
import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

Now, we have to create a character pool with the different character sets such as alphanumeric, alphabetic, lowercase alphabetic with special characters, lowercase alphanumeric, hexadecimal, numeric, and non-zero numeric values.

switch format {
case "alnum":
    pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
case "alpSpecLower":
    pool = "abcdefghijklmnopqrstuvwxyz-_"
case "alpha":
    pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
case "alpNumLower":
    pool = "0123456789abcdefghijklmnopqrstuvwxyz"
case "hexdec":
    pool = "0123456789abcdef"
case "numeric":
    pool = "0123456789"
case "nozero":
    pool = "123456789"
default:
    return ""
}

To ensure the generated random strings are unpredictable, we seed the random number generator using the current time.

rand.Seed(time.Now().UnixNano())

After that, We create a byte slice called buf with the specified length and fill it with random characters from the selected pool.

buf := make([]byte, length)

for i := range buf {
	buf[i] = pool[rand.Intn(len(pool))]
}

Here is the detailed example program of how to generate a random string using golang:

package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

func randomHash(format string, length int) string {
	pool := ""

	switch format {
	case "alnum":
		pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	case "alpSpecLower":
		pool = "abcdefghijklmnopqrstuvwxyz-_"
	case "alpha":
		pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	case "alpNumLower":
		pool = "0123456789abcdefghijklmnopqrstuvwxyz"
	case "hexdec":
		pool = "0123456789abcdef"
	case "numeric":
		pool = "0123456789"
	case "nozero":
		pool = "123456789"
	default:
		return ""
	}

	rand.Seed(time.Now().UnixNano())
	buf := make([]byte, length)

	for i := range buf {
		buf[i] = pool[rand.Intn(len(pool))]
	}

	return string(buf)
}

func main() {
	fmt.Println("alnum :", randomHash("alnum", 10))
	fmt.Println("alpSpecLower :", randomHash("alpSpecLower", 10))
	fmt.Println("alpha :", randomHash("alpha", 10))
	fmt.Println("alpNumLower :", randomHash("alpNumLower", 10))
	fmt.Println("hexdec :", randomHash("hexdec", 10))
	fmt.Println("numeric :", randomHash("numeric", 10))
	fmt.Println("nozero :", randomHash("nozero", 10))
}

Categorized in:

Tagged in: