-
Notifications
You must be signed in to change notification settings - Fork 97
/
random_data.go
443 lines (376 loc) · 11.4 KB
/
random_data.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Package randomdata implements a bunch of simple ways to generate (pseudo) random data
package randomdata
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net"
"strconv"
"strings"
"sync"
"time"
"unicode"
)
const (
Male int = 0
Female int = 1
RandomGender int = 2
)
const (
Small int = 0
Large int = 1
)
const (
FullCountry = 0
TwoCharCountry = 1
ThreeCharCountry = 2
)
const (
DateInputLayout = "2006-01-02"
DateOutputLayout = "Monday 2 Jan 2006"
)
const ALPHANUMERIC = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
type jsonContent struct {
Adjectives []string `json:"adjectives"`
Nouns []string `json:"nouns"`
FirstNamesFemale []string `json:"firstNamesFemale"`
FirstNamesMale []string `json:"firstNamesMale"`
LastNames []string `json:"lastNames"`
Domains []string `json:"domains"`
People []string `json:"people"`
StreetTypes []string `json:"streetTypes"` // Taken from https://github.com/tomharris/random_data/blob/master/lib/random_data/locations.rb
Paragraphs []string `json:"paragraphs"` // Taken from feedbooks.com and www.gutenberg.org
Countries []string `json:"countries"` // Fetched from the world bank at http://siteresources.worldbank.org/DATASTATISTICS/Resources/CLASS.XLS
CountriesThreeChars []string `json:"countriesThreeChars"`
CountriesTwoChars []string `json:"countriesTwoChars"`
Currencies []string `json:"currencies"` //https://github.com/OpenBookPrices/country-data
Cities []string `json:"cities"`
States []string `json:"states"`
StatesSmall []string `json:"statesSmall"`
Days []string `json:"days"`
Months []string `json:"months"`
FemaleTitles []string `json:"femaleTitles"`
MaleTitles []string `json:"maleTitles"`
Timezones []string `json:"timezones"` // https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Locales []string `json:"locales"` // https://tools.ietf.org/html/bcp47
UserAgents []string `json:"userAgents"` // http://techpatterns.com/downloads/firefox/useragentswitcher.xml
CountryCallingCodes []string `json:"countryCallingCodes"` // from https://github.com/datasets/country-codes/blob/master/data/country-codes.csv
ProvincesGB []string `json:"provincesGB"`
StreetNameGB []string `json:"streetNameGB"`
StreetTypesGB []string `json:"streetTypesGB"`
}
type pRand struct {
pr *rand.Rand
mu *sync.Mutex
}
func (r *pRand) Intn(n int) int {
r.mu.Lock()
defer r.mu.Unlock()
return r.pr.Intn(n)
}
func (r *pRand) Float64() float64 {
r.mu.Lock()
defer r.mu.Unlock()
return r.pr.Float64()
}
var jsonData = jsonContent{}
var privateRand *pRand
func init() {
privateRand = &pRand{rand.New(rand.NewSource(time.Now().UnixNano())), &sync.Mutex{}}
jsonData = jsonContent{}
err := json.Unmarshal(data, &jsonData)
if err != nil {
log.Fatal(err)
}
}
func CustomRand(randToUse *rand.Rand) {
privateRand.pr = randToUse
}
// Returns a random part of a slice
func randomFrom(source []string) string {
return source[privateRand.Intn(len(source))]
}
// Title returns a random title, gender decides the gender of the name
func Title(gender int) string {
switch gender {
case Male:
return randomFrom(jsonData.MaleTitles)
case Female:
return randomFrom(jsonData.FemaleTitles)
default:
return Title(privateRand.Intn(2))
}
}
// FirstName returns a random first name, gender decides the gender of the name
func FirstName(gender int) string {
var name = ""
switch gender {
case Male:
name = randomFrom(jsonData.FirstNamesMale)
break
case Female:
name = randomFrom(jsonData.FirstNamesFemale)
break
default:
name = FirstName(rand.Intn(2))
break
}
return name
}
// LastName returns a random last name
func LastName() string {
return randomFrom(jsonData.LastNames)
}
// FullName returns a combination of FirstName LastName randomized, gender decides the gender of the name
func FullName(gender int) string {
return FirstName(gender) + " " + LastName()
}
// Email returns a random email
func Email() string {
return strings.ToLower(FirstName(RandomGender)+LastName()) + StringNumberExt(1, "", 3) + "@" + randomFrom(jsonData.Domains)
}
// Country returns a random country, countryStyle decides what kind of format the returned country will have
func Country(countryStyle int64) string {
country := ""
switch countryStyle {
default:
case FullCountry:
country = randomFrom(jsonData.Countries)
break
case TwoCharCountry:
country = randomFrom(jsonData.CountriesTwoChars)
break
case ThreeCharCountry:
country = randomFrom(jsonData.CountriesThreeChars)
break
}
return country
}
// Currency returns a random currency under ISO 4217 format
func Currency() string {
return randomFrom(jsonData.Currencies)
}
// City returns a random city
func City() string {
return randomFrom(jsonData.Cities)
}
// ProvinceForCountry returns a randomly selected province (state, county,subdivision ) name for a supplied country.
// If the country is not supported it will return an empty string.
func ProvinceForCountry(countrycode string) string {
switch countrycode {
case "US":
return randomFrom(jsonData.States)
case "GB":
return randomFrom(jsonData.ProvincesGB)
}
return ""
}
// State returns a random american state
func State(typeOfState int) string {
if typeOfState == Small {
return randomFrom(jsonData.StatesSmall)
}
return randomFrom(jsonData.States)
}
// Street returns a random fake street name
func Street() string {
return fmt.Sprintf("%s %s", randomFrom(jsonData.People), randomFrom(jsonData.StreetTypes))
}
// StreetForCountry returns a random fake street name typical to the supplied country.
// If the country is not supported it will return an empty string.
func StreetForCountry(countrycode string) string {
switch countrycode {
case "US":
return Street()
case "GB":
return fmt.Sprintf("%s %s", randomFrom(jsonData.StreetNameGB), randomFrom(jsonData.StreetTypesGB))
}
return ""
}
// Address returns an american style address
func Address() string {
return fmt.Sprintf("%d %s,\n%s, %s, %s", Number(100), Street(), City(), State(Small), PostalCode("US"))
}
// Paragraph returns a random paragraph
func Paragraph() string {
return randomFrom(jsonData.Paragraphs)
}
// Number returns a random number, if only one integer (n1) is supplied it returns a number in [0,n1)
// if a second argument is supplied it returns a number in [n1,n2)
func Number(numberRange ...int) int {
nr := 0
if len(numberRange) > 1 {
nr = 1
nr = privateRand.Intn(numberRange[1]-numberRange[0]) + numberRange[0]
} else {
nr = privateRand.Intn(numberRange[0])
}
return nr
}
func Decimal(numberRange ...int) float64 {
nr := 0.0
if len(numberRange) > 1 {
nr = 1.0
nr = privateRand.Float64()*(float64(numberRange[1])-float64(numberRange[0])) + float64(numberRange[0])
} else {
nr = privateRand.Float64() * float64(numberRange[0])
}
if len(numberRange) > 2 {
sf := strconv.FormatFloat(nr, 'f', numberRange[2], 64)
nr, _ = strconv.ParseFloat(sf, 64)
}
return nr
}
func StringNumberExt(numberPairs int, separator string, numberOfDigits int) string {
numberString := ""
for i := 0; i < numberPairs; i++ {
for d := 0; d < numberOfDigits; d++ {
numberString += fmt.Sprintf("%d", Number(0, 9))
}
if i+1 != numberPairs {
numberString += separator
}
}
return numberString
}
// StringNumber returns a random number as a string
func StringNumber(numberPairs int, separator string) string {
return StringNumberExt(numberPairs, separator, 2)
}
// StringSample returns a random string from a list of strings
func StringSample(stringList ...string) string {
str := ""
if len(stringList) > 0 {
str = stringList[Number(0, len(stringList))]
}
return str
}
// Alphanumeric returns a random alphanumeric string consits of [0-9a-zA-Z].
func Alphanumeric(length int) string {
list := make([]byte, length)
for i := range list {
list[i] = ALPHANUMERIC[privateRand.Intn(len(ALPHANUMERIC))]
}
return string(list)
}
func Boolean() bool {
nr := privateRand.Intn(2)
return nr != 0
}
// Noun returns a random noun
func Noun() string {
return randomFrom(jsonData.Nouns)
}
// Adjective returns a random adjective
func Adjective() string {
return randomFrom(jsonData.Adjectives)
}
func uppercaseFirstLetter(word string) string {
a := []rune(word)
a[0] = unicode.ToUpper(a[0])
return string(a)
}
func lowercaseFirstLetter(word string) string {
a := []rune(word)
a[0] = unicode.ToLower(a[0])
return string(a)
}
// SillyName returns a silly name, useful for randomizing naming of things
func SillyName() string {
return uppercaseFirstLetter(Noun()) + Adjective()
}
// IpV4Address returns a valid IPv4 address as string
func IpV4Address() string {
blocks := []string{}
for i := 0; i < 4; i++ {
number := privateRand.Intn(255)
blocks = append(blocks, strconv.Itoa(number))
}
return strings.Join(blocks, ".")
}
// IpV6Address returns a valid IPv6 address as net.IP
func IpV6Address() string {
var ip net.IP
for i := 0; i < net.IPv6len; i++ {
number := uint8(privateRand.Intn(255))
ip = append(ip, number)
}
return ip.String()
}
// MacAddress returns an mac address string
func MacAddress() string {
blocks := []string{}
for i := 0; i < 6; i++ {
number := fmt.Sprintf("%02x", privateRand.Intn(255))
blocks = append(blocks, number)
}
return strings.Join(blocks, ":")
}
// Day returns random day
func Day() string {
return randomFrom(jsonData.Days)
}
// Month returns random month
func Month() string {
return randomFrom(jsonData.Months)
}
// FullDate returns full date
func FullDate() string {
timestamp := time.Now()
year := timestamp.Year()
month := Number(1, 13)
maxDay := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC).Day()
day := Number(1, maxDay+1)
date := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
return date.Format(DateOutputLayout)
}
// FullDateInRange returns a date string within a given range, given in the format "2006-01-02".
// If no argument is supplied it will return the result of randomdata.FullDate().
// If only one argument is supplied it is treated as the max date to return.
// If a second argument is supplied it returns a date between (and including) the two dates.
// Returned date is in format "Monday 2 Jan 2006".
func FullDateInRange(dateRange ...string) string {
var (
min time.Time
max time.Time
duration int
dateString string
)
if len(dateRange) == 1 {
max, _ = time.Parse(DateInputLayout, dateRange[0])
} else if len(dateRange) == 2 {
min, _ = time.Parse(DateInputLayout, dateRange[0])
max, _ = time.Parse(DateInputLayout, dateRange[1])
}
if !max.IsZero() && max.After(min) {
duration = Number(int(max.Sub(min))) * -1
dateString = max.Add(time.Duration(duration)).Format(DateOutputLayout)
} else if !max.IsZero() && !max.After(min) {
dateString = max.Format(DateOutputLayout)
} else {
dateString = FullDate()
}
return dateString
}
func Timezone() string {
return randomFrom(jsonData.Timezones)
}
func Locale() string {
return randomFrom(jsonData.Locales)
}
func UserAgentString() string {
return randomFrom(jsonData.UserAgents)
}
func PhoneNumber() string {
str := randomFrom(jsonData.CountryCallingCodes) + " "
str += Digits(privateRand.Intn(3) + 1)
for {
// max 15 chars
remaining := 15 - (len(str) - strings.Count(str, " "))
if remaining < 2 {
return "+" + str
}
str += " " + Digits(privateRand.Intn(remaining-1)+1)
}
}