Generate random hex string in Go
Posted on 15 Dec 2014
    
  In Ruby you can call a simple and convenient function SecureRandom.hex to make a
string of preferred size filled with hexadecimals.
Example:
require "secureranom"
SecureRandom.hex(20)
# => bfa620013597e9c30c179037ad74527a4956a561
Here's a quick snippet of how to make its alternative in Go:
package main
import (
  "crypto/rand"
  "encoding/hex"
  "fmt"
)
func randomHex(n int) (string, error) {
  bytes := make([]byte, n)
  if _, err := rand.Read(bytes); err != nil {
    return "", err
  }
  return hex.EncodeToString(bytes), nil
}
func main() {
  val, _ := randomHex(20)
  fmt.Println(val)
}