github.com/goldeneggg/goa@v1.3.1/design/random.go (about) 1 package design 2 3 import ( 4 "crypto/md5" 5 "encoding/binary" 6 "math/rand" 7 "time" 8 9 "github.com/manveru/faker" 10 "github.com/satori/go.uuid" 11 ) 12 13 // RandomGenerator generates consistent random values of different types given a seed. 14 // The random values are consistent in that given the same seed the same random values get 15 // generated. 16 type RandomGenerator struct { 17 Seed string 18 faker *faker.Faker 19 rand *rand.Rand 20 } 21 22 // NewRandomGenerator returns a random value generator seeded from the given string value. 23 func NewRandomGenerator(seed string) *RandomGenerator { 24 hasher := md5.New() 25 hasher.Write([]byte(seed)) 26 sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil))) 27 source := rand.NewSource(sint) 28 ran := rand.New(source) 29 faker := &faker.Faker{ 30 Language: "end", 31 Dict: faker.Dict["en"], 32 Rand: ran, 33 } 34 return &RandomGenerator{ 35 Seed: seed, 36 faker: faker, 37 rand: ran, 38 } 39 } 40 41 // Int produces a random integer. 42 func (r *RandomGenerator) Int() int { 43 return r.rand.Int() 44 } 45 46 // String produces a random string. 47 func (r *RandomGenerator) String() string { 48 return r.faker.Sentence(2, false) 49 50 } 51 52 // DateTime produces a random date. 53 func (r *RandomGenerator) DateTime() time.Time { 54 // Use a constant max value to make sure the same pseudo random 55 // values get generated for a given API. 56 max := time.Date(2016, time.July, 11, 23, 0, 0, 0, time.UTC).Unix() 57 unix := r.rand.Int63n(max) 58 return time.Unix(unix, 0).UTC() 59 } 60 61 // UUID produces a random UUID. 62 func (r *RandomGenerator) UUID() uuid.UUID { 63 return uuid.Must(uuid.NewV4()) 64 } 65 66 // Bool produces a random boolean. 67 func (r *RandomGenerator) Bool() bool { 68 return r.rand.Int()%2 == 0 69 } 70 71 // Float64 produces a random float64 value. 72 func (r *RandomGenerator) Float64() float64 { 73 return r.rand.Float64() 74 }