Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/strings/go$ _

Generate Random Strings in Go

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Go

What: Generate random strings in Go using <code>crypto/rand</code> for cryptographically secure random generation. Perfect for microservices and backend systems.

Try it: Use our interactive Strings generator or integrate this code into your Go application.

Generate random strings in Go using crypto/rand for cryptographically secure random generation. Perfect for microservices and backend systems. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Ruby or use our interactive web generator.

Go Code Example

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

const (
    alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    hexChars     = "0123456789abcdef"
)

func generateRandomString(length int, customChars string) (string, error) {
    if customChars == "" {
        customChars = alphanumeric
    }

    result := make([]byte, length)
    charsLen := big.NewInt(int64(len(customChars)))

    for i := 0; i < length; i++ {
        num, err := rand.Int(rand.Reader, charsLen)
        if err != nil {
            return "", err
        }
        result[i] = customChars[num.Int64()]
    }

    return string(result), nil
}

func main() {
    // Generate a 16-character alphanumeric string
    randomString, _ := generateRandomString(16, "")
    fmt.Println(randomString)  // Example: aB3xY7mN2pQ9zR5t

    // Generate a 12-character hex string
    hexString, _ := generateRandomString(12, hexChars)
    fmt.Println(hexString)  // Example: a3f7b2e9c4d1

    // Generate a 10-character lowercase string
    lowercaseString, _ := generateRandomString(10, "abcdefghijklmnopqrstuvwxyz")
    fmt.Println(lowercaseString)  // Example: xmkpqrstuv
}

[EXPLANATION]

crypto/rand.Int() provides cryptographically secure random integers. This implementation properly handles errors and uses big.Int for secure index generation. The function accepts custom character sets for flexible string generation.

Expected Output

aB3xY7mN2pQ9zR5t
a3f7b2e9c4d1
xmkpqrstuv

Common Use Cases

  • Microservices session token generation
  • RESTful API unique identifiers
  • Kubernetes pod correlation IDs
  • gRPC request tracking IDs
  • Database record unique keys
  • Cache key generation

Important Notes

  • Always use crypto/rand for secure string generation
  • Handle errors properly in production code
  • rand.Reader provides cryptographically secure random bytes
  • Consider using encoding/base64 for URL-safe strings

Try Our Interactive Generator

Don't want to write code? Use our free web-based Strings generator with instant results.

TRY STRINGS GENERATOR →