Skip to content

Instantly share code, notes, and snippets.

@rjeczalik
Last active August 29, 2015 14:25
Show Gist options
  • Save rjeczalik/3ae26428fe203294630a to your computer and use it in GitHub Desktop.
Save rjeczalik/3ae26428fe203294630a to your computer and use it in GitHub Desktop.
rand helper
package main
import (
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
var (
min = flag.Int64("min", 0, "min length of string, int")
max = flag.Int64("max", math.MaxInt64, "max length of string, int")
typ = flag.String("type", "int", "available: string, int, time, date")
)
func nmin(i, j int) int {
if i < j {
return i
}
return j
}
func die(v interface{}) {
fmt.Fprintln(os.Stderr, v)
os.Exit(1)
}
func main() {
flag.Parse()
if n, err := strconv.ParseInt(os.Getenv("RAND_MIN"), 10, 64); err == nil {
*min = n
}
if n, err := strconv.ParseInt(os.Getenv("RAND_MAX"), 10, 64); err == nil {
*max = n
}
if s := os.Getenv("RAND_TYPE"); s != "" {
*typ = s
}
rand.Seed(time.Now().UnixNano() + int64(os.Getpid()))
*typ = strings.ToLower(*typ)
switch *typ {
case "date", "time":
*max = 4102444800
}
*max -= *min
n := *min + rand.Int63n(*max)
switch *typ {
case "string":
hash := sha256.New()
fmt.Fprint(hash, n)
fmt.Println(hex.EncodeToString(hash.Sum(nil))[:nmin(int(*max), sha256.Size)])
case "int":
fmt.Println(n)
case "time":
fmt.Println(time.Unix(n, 0).Format("15:04:05"))
case "date":
fmt.Println(time.Unix(n, 0).Format("2006-01-02"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment