Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Golang] How use Ramdom in Golang

Posted on March 1, 2022September 19, 2024 By nim No Comments on [Golang] How use Ramdom in Golang

Hướng dẫn sử dụng random trong golang

Nhưng sau đây là function đầy đủ mà bạn có thể tham khảo

Contents

Toggle
  • Generating a Secure Random String in Go: Step-by-Step Guide
    • Overview of the Function
    • Step 1: Character Set
    • Step 2: Convert the Character Set to Runes
    • Step 3: Generate a Random Index
    • Step 4: Build the Random String
    • Step 5: Return the Random String
    • Step 6: Handling Errors
    • Step 7: Using the Function
    • Conclusion
    • What’s Next?

Generating a Secure Random String in Go: Step-by-Step Guide

In many applications, whether it’s generating API keys, secure tokens, or simply creating unique identifiers, the need for a random string generator is common. In this blog post, we’ll walk through a Go function that generates secure random strings of a specified length using characters from a predefined set. We will also explain each part of the code for easy understanding.

Overview of the Function

The randomString function generates a string of random characters by selecting from a predefined set of characters. It uses Go’s crypto/rand package, which provides cryptographically secure random numbers, making this function ideal for security-sensitive applications.

Here’s the function we’ll be covering:

package main

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

const randomStringSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321_+="

// Function to generate a random string of length n
func randomString(n int) string {
    // Slice to hold the generated runes
    result := make([]rune, n)
    // Convert randomStringSource to a slice of runes
    sourceRunes := []rune(randomStringSource)
    // Get the length of the source runes
    sourceLen := big.NewInt(int64(len(sourceRunes)))

    // Loop to generate each random character
    for i := range result {
        // Generate a random index within the bounds of sourceRunes
        randomIndex, err := rand.Int(rand.Reader, sourceLen)
        if err != nil {
            panic(err) // Handle error, it shouldn't happen often
        }
        // Assign the random rune to the result
        result[i] = sourceRunes[randomIndex.Int64()]
    }

    // Return the generated string
    return string(result)
}

func main() {
    // Generate and print a random string of length 20
    fmt.Println(randomString(20))
}

Now, let’s break it down.

Step 1: Character Set

We start by defining the character set from which the random string will be generated. In this case, it’s a combination of lowercase letters, uppercase letters, digits, and some special characters:

const randomStringSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321_+="

This randomStringSource is a string of allowed characters, and later, we’ll randomly pick characters from this set to form our random string.

Step 2: Convert the Character Set to Runes

Go strings are made up of bytes, but since we’re dealing with potentially multi-byte characters (even though we only use single-byte characters here), we convert our randomStringSource into a slice of runes:

sourceRunes := []rune(randomStringSource)

Runes in Go are a representation of Unicode characters, and by converting our string to a slice of runes, we ensure that we handle each character correctly, even if it’s multi-byte.

Step 3: Generate a Random Index

To generate a random string, we need to randomly select characters from the sourceRunes. For this, we generate random indices in the range of the length of sourceRunes. We use crypto/rand.Int to securely generate these random indices:

sourceLen := big.NewInt(int64(len(sourceRunes)))

This line stores the length of our sourceRunes as a *big.Int (since rand.Int requires that type). Then, in a loop, we generate random numbers to use as indices:

randomIndex, err := rand.Int(rand.Reader, sourceLen)

This line generates a random *big.Int in the range [0, len(sourceRunes)-1]. The rand.Reader is used here because it provides cryptographically secure random numbers.

Step 4: Build the Random String

Once we have the random index, we use it to select a character from the sourceRunes. We repeat this process for the desired length of the random string:

result[i] = sourceRunes[randomIndex.Int64()]

This assigns a random character to the current position in the result slice.

Step 5: Return the Random String

After the loop is done, we convert the result slice (which holds the random runes) back to a string and return it:

return string(result)

Step 6: Handling Errors

If for some reason the random number generation fails (which is rare when using rand.Reader), we panic. This ensures that our program doesn’t silently fail:

if err != nil {
    panic(err)
}

While panic may not be ideal in production code, it’s acceptable here because we are writing a utility function where failure is highly unlikely and should be caught early.

Step 7: Using the Function

To use the randomString function, we simply call it with the desired string length. For example, to generate a random string of length 20:

fmt.Println(randomString(20))

This will print a secure random string like Yz23FgB1_cHkXpT2Q+=A.

Conclusion

This randomString function is an excellent tool for generating cryptographically secure random strings in Go. It can be used in a variety of scenarios where unique, unpredictable strings are needed, such as generating passwords, tokens, or unique identifiers.

Key Takeaways:

  • We used Go’s crypto/rand package for secure random number generation.
  • The character set is customizable, allowing for flexibility in the types of strings you want to generate.
  • The function is simple and efficient while maintaining security standards.

What’s Next?

You could extend this function to:

  1. Allow for custom character sets.
  2. Add error handling to gracefully handle cases where random number generation fails.
  3. Adjust the random string length for specific use cases.

This function can be a crucial part of security mechanisms in your Go applications, ensuring that random strings are both unpredictable and secure.


Happy coding!

Golang

Post navigation

Previous Post: [wordpress] Setuping WordPress becomes a private note web!
Next Post: [OnlyOffice/Collabora] Install open-source web-based office for NextCloud

More Related Articles

[Golang] Return Error in Golang Golang
[Golang] Looking filepath.Walk to return any file and children folder in the folder Golang
[Golang] The declarations are very helpful in Golang Golang
[Golang] Thiết kế model trong golang và echo framework. Golang
[Golang] Error obtaining VCS status: exit status 128 Golang
[Golang] Split or Cut a string many small pieces with Golang Golang

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Azure/Loadbalancer] Creating an internal load balancer on Azure Kubernetes Service (AKS). May 13, 2025
  • [Azure] The subscription is not registered to use namespace ‘Microsoft.ContainerService’ May 8, 2025
  • [Azure] Insufficient regional vcpu quota left May 8, 2025
  • [WordPress] How to add a Dynamic watermark on WordPress. May 6, 2025
  • [vnet/Azure] VNet provisioning via Terraform. April 28, 2025

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.