Technical Documentation: brianvoe/gofakeit
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
Gofakeit [](https://goreportcard.com/report/github.com/brianvoe/gofakeit) [](https://godoc.org/github.com/brianvoe/gofakeit/v7) [](https://raw.githubusercontent.com/brianvoe/gofakeit/master/LICENSE.txt)
Random data generator written in go
Support
Merch
Features
- 310+ Functions!!!
- Random Sources
- Global Rand
- Struct Generator
- Custom Functions
- Templates
- Http Server
- Command Line Tool
- Zero dependencies
- Benchmarks
- Issue
Contributors
Thank you to all our Gofakeit contributors!
Installation
go get github.com/brianvoe/gofakeit/v7Simple Usage
import "github.com/brianvoe/gofakeit/v7"
gofakeit.Name() // Markus Moen
gofakeit.Email() // [email protected]
gofakeit.Phone() // (570)245-7485
gofakeit.BS() // front-end
gofakeit.BeerName() // Duvel
gofakeit.Color() // MediumOrchid
gofakeit.Company() // Moen, Pagac and Wuckert
gofakeit.CreditCardNumber(nil) // 4287271570245748
gofakeit.HackerPhrase() // Connecting the array won't do anything, we need to generate the haptic COM driver!
gofakeit.JobTitle() // Director
gofakeit.CurrencyShort() // USDSeed
If you are using the default global usage and dont care about seeding no need to set anything.
Gofakeit will seed it with a cryptographically secure number.
If you need a reproducible outcome you can set it via the Seed function call. Every example in
this repo sets it for testing purposes.
import "github.com/brianvoe/gofakeit/v7"
gofakeit.Seed(0) // If 0 will use crypto/rand to generate a number
// or
gofakeit.Seed(8675309) // Set it to whatever number you wantRandom Sources
Gofakeit has a few rand sources, by default it uses math/rand/v2 PCG which is a pseudo random number generator and is thread locked.
If you want to see other potential sources you can see the sub package Source for more information.
import (
"github.com/brianvoe/gofakeit/v7"
"github.com/brianvoe/gofakeit/v7/source"
"math/rand/v2"
)
// Uses math/rand/v2(PCG Pseudo) with mutex locking
faker := gofakeit.New(0)
// NewFaker takes in a source and whether or not it should be thread safe
faker := gofakeit.NewFaker(src rand.Source, lock bool)
// PCG Pseudo
faker := gofakeit.NewFaker(rand.NewPCG(11, 11), true)
// ChaCha8
faker := gofakeit.NewFaker(rand.NewChaCha8([32]byte{0, 1, 2, 3, 4, 5}), true)
// Additional from Gofakeit sub package source
// JSF(Jenkins Small Fast)
faker := gofakeit.NewFaker(source.NewJSF(11), true)
// SFC(Simple Fast Counter)
faker := gofakeit.NewFaker(source.NewSFC(11), true)
// Crypto - Uses crypto/rand
faker := gofakeit.NewFaker(source.NewCrypto(), true)
// Dumb - simple incrementing number
faker := gofakeit.NewFaker(source.NewDumb(11), true)Global Rand Set
If you would like to use the simple function calls but need to use something like
crypto/rand you can override the default global with the random source that you want.
import "github.com/brianvoe/gofakeit/v7"
gofakeit.GlobalFaker = gofakeit.New(0)Struct
Gofakeit can generate random data for struct fields. For the most part it covers all the basic type
as well as some non-basic like time.Time.
Struct fields can also use tags to more specifically generate data for that field type.
/* Detailed source-code truncated for AI context efficiency. */Fakeable types
It is possible to extend a struct by implementing the Fakeable interface
in order to control the generation.
For example, this is useful when it is not possible to modify the struct that you want to fake by adding struct tags to a field but you still need to be able to control the generation process.
// Custom string that you want to generate your own data for
type Friend string
func (c *Friend) Fake(f *gofakeit.Faker) (any, error) {
// Can call any other faker methods
return f.RandomString([]string{"billy", "fred", "susan"}), nil
}
// Custom time that you want to generate your own data for
type Age time.Time
func (c *Age) Fake(f *gofakeit.Faker) (any, error) {
return Age(f.DateRange(time.Now().AddDate(-100, 0, 0), time.Now().AddDate(-18, 0, 0))), nil
}
// This is the struct that we cannot modify to add struct tags
type User struct {
Name Friend
Age *Age
}
var u User
gofakeit.Struct(&u)
fmt.Println(u.Name) // billy
fmt.Println(time.Time(*u.Age)) // 1990-12-07 04:14:25.685339029 +0000 UTCCustom Functions
In a lot of situations you may need to use your own random function usage for your specific needs.
If you would like to extend the usage of struct tags, generate function, available usages in the gofakeit server
or gofakeit command sub packages. You can do so via the AddFuncLookup. Each function has their own lookup, if
you need more reference examples you can look at each files lookups.
// Simple
gofakeit.AddFuncLookup("friendname", gofakeit.Info{
Category: "custom",
Description: "Random friend name",
Example: "bill",
Output: "string",
Generate: func(f *gofakeit.Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) {
return f.RandomString([]string{"bill", "bob", "sally"}), nil
},
})
// With Params
gofakeit.AddFuncLookup("jumbleword", gofakeit.Info{
Category: "jumbleword",
Description: "Take a word and jumble it up",
Example: "loredlowlh",
Output: "string",
Params: []gofakeit.Param{
{Field: "word", Type: "string", Description: "Word you want to jumble"},
},
Generate: func(f *gofakeit.Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) {
word, err := info.GetString(m, "word")
if err != nil {
return nil, err
}
split := strings.Split(word, "")
f.ShuffleStrings(split)
return strings.Join(split, ""), nil
},
})
type Foo struct {
FriendName string `fake:"{friendname}"`
JumbleWord string `fake:"{jumbleword:helloworld}"`
}
var f Foo
gofakeit.Struct(&f)
fmt.Println(f.FriendName) // bill
fmt.Println(f.JumbleWord) // loredlowlhTemplates
Generate custom outputs using golang's template engine https://pkg.go.dev/text/template.
We have added all the available functions to the template engine as well as some additional ones that are useful for template building.
Additional Available Functions
- ToUpper(s string) string // Make string upper case
- ToLower(s string) string // Make string lower case
- ToString(s any) // Convert to string
- ToDate(s string) time.Time // Convert string to date
- SpliceAny(args ...any) []any // Build a slice of anys, used with Weighted
- SpliceString(args ...string) []string // Build a slice of strings, used with Teams and RandomString
- SpliceUInt(args ...uint) []uint // Build a slice of uint, used with Dice and RandomUint
- SpliceInt(args ...int) []int // Build a slice of int, used with RandomIntUnavailable Gofakeit functions
// Any functions that dont have a return value
- AnythingThatReturnsVoid(): void
// Not available to use in templates
- Template(co *TemplateOptions) ([]byte, error)
- RandomMapKey(mapI any) anyExample Usages
import "github.com/brianvoe/gofakeit/v7"
func main() {
// Accessing the Lines variable from within the template.
template := `
Subject: {{RandomString (SliceString "Greetings" "Hello" "Hi")}}
Dear {{LastName}},
{{RandomString (SliceString "Greetings!" "Hello there!" "Hi, how are you?")}}
{{Paragraph 1 5 10 "\n\n"}}
{{RandomString (SliceString "Warm regards" "Best wishes" "Sincerely")}}
{{$person:=Person}}
{{$person.FirstName}} {{$person.LastName}}
{{$person.Contact.Email}}
{{$person.Contact.Phone}}
`
value, err := gofakeit.Template(template, &gofakeit.TemplateOptions{Data: 5})
if err != nil {
fmt.Println(err)
}
fmt.Println(value)
}Output:
Subject: Hello
Dear Krajcik,
Greetings!
Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem.
Warm regards
Kaitlyn Krajcik
kaitlynkrajcik@krajcik
570-245-7485Functions
All functions also exist as methods on the Faker struct
File
Passing nil to CSV, JSON or XML will auto generate data using default values.
CSV(co *CSVOptions) ([]byte, error)
JSON(jo *JSONOptions) ([]byte, error)
XML(xo *XMLOptions) ([]byte, error)
FileExtension() string
FileMimeType() stringTemplate
Passing nil will auto generate data using default values.
Template(co *TemplateOptions) (string, error)
Markdown(co *MarkdownOptions) (string, error)
EmailText(co *EmailOptions) (string, error)
FixedWidth(co *FixedWidthOptions) (string, error)ID
ID() string
UUID() stringProduct
Product() *ProductInfo
ProductName() string
ProductDescription() string
ProductCategory() string
ProductFeature() string
ProductMaterial() string
ProductUPC() string
ProductAudience() string
ProductDimension() string
ProductUseCase() string
ProductBenefit() string
ProductSuffix() string
ProductISBN(opts *ISBNOptions) stringPerson
Person() *PersonInfo
Name() string
NamePrefix() string
NameSuffix() string
FirstName() string
MiddleName() string
LastName() string
Gender() string
Age() int
Ethnicity() string
SSN() string
EIN() string
Hobby() string
SocialMedia() string
Bio() string
Contact() *ContactInfo
Email() string
Phone() string
PhoneFormatted() string
Teams(peopleArray []string, teamsArray []string) map[string][]stringGenerate
Struct(v any)
Slice(v any)
Map() map[string]any
Generate(value string) string
Regex(value string) stringDatabase
SQL(so *SQLOptions) (string, error)Auth
Username() string
Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) stringAddress
Address() *AddressInfo
City() string
Country() string
CountryAbr() string
State() string
StateAbr() string
Street() string
StreetName() string
StreetNumber() string
StreetPrefix() string
StreetSuffix() string
Unit() string
Zip() string
Latitude() float64
LatitudeInRange(min, max float64) (float64, error)
Longitude() float64
LongitudeInRange(min, max float64) (float64, error)Airline
AirlineAircraftType() string
AirlineAirplane() string
AirlineAirport() string
AirlineAirportIATA() string
AirlineFlightNumber() string
AirlineRecordLocator() string
AirlineSeat() stringGame
Gamertag() string
Dice(numDice uint, sides []uint) []uintBeer
BeerAlcohol() string
BeerBlg() string
BeerHop() string
BeerIbu() string
BeerMalt() string
BeerName() string
BeerStyle() string
BeerYeast() stringCar
Car() *CarInfo
CarMaker() string
CarModel() string
CarType() string
CarFuelType() string
CarTransmissionType() stringWords
/* Detailed source-code truncated for AI context efficiency. */Foods
Fruit() string
Vegetable() string
Breakfast() string
Lunch() string
Dinner() string
Snack() string
Dessert() string
Drink() stringMisc
Bool() bool
Weighted(options []any, weights []float32) (any, error)
FlipACoin() string
RandomMapKey(mapI any) any
ShuffleAnySlice(v any)Colors
Color() string
HexColor() string
RGBColor() []int
HSLColor() []int
SafeColor() string
NiceColors() stringImages
Image(width int, height int) *img.RGBA
ImageJpeg(width int, height int) []byte
ImagePng(width int, height int) []byteInternet
URL() string
UrlSlug(words int) string
DomainName() string
DomainSuffix() string
IPv4Address() string
IPv6Address() string
MacAddress() string
HTTPStatusCode() string
HTTPStatusCodeSimple() int
LogLevel(logType string) string
HTTPMethod() string
HTTPVersion() string
UserAgent() string
ChromeUserAgent() string
FirefoxUserAgent() string
OperaUserAgent() string
SafariUserAgent() string
APIUserAgent() stringHTML
InputName() string
Svg(options *SVGOptions) stringDate/Time
Date() time.Time
PastDate() time.Time
FutureDate() time.Time
DateRange(start, end time.Time) time.Time
NanoSecond() int
Second() int
Minute() int
Hour() int
Month() int
MonthString() string
Day() int
WeekDay() string
Year() int
TimeZone() string
TimeZoneAbv() string
TimeZoneFull() string
TimeZoneOffset() float32
TimeZoneRegion() stringPayment
Price(min, max float64) float64
CreditCard() *CreditCardInfo
CreditCardCvv() string
CreditCardExp() string
CreditCardNumber(*CreditCardOptions) string
CreditCardType() string
Currency() *CurrencyInfo
CurrencyLong() string
CurrencyShort() string
AchRouting() string
AchAccount() string
BitcoinAddress() string
BitcoinPrivateKey() string
BankName() string
BankType() stringFinance
Cusip() string
Isin() stringCompany
BS() string
Blurb() string
BuzzWord() string
Company() string
CompanySuffix() string
Job() *JobInfo
JobDescriptor() string
JobLevel() string
JobTitle() string
Slogan() stringHacker
HackerAbbreviation() string
HackerAdjective() string
HackeringVerb() string
HackerNoun() string
HackerPhrase() string
HackerVerb() stringHipster
HipsterWord() string
HipsterSentence() string
HipsterParagraph() stringApp
AppName() string
AppVersion() string
AppAuthor() stringAnimal
PetName() string
Animal() string
AnimalType() string
FarmAnimal() string
Cat() string
Dog() string
Bird() stringEmoji
Emoji() string
EmojiCategory() string
EmojiAlias() string
EmojiTag() string
EmojiFlag() string
EmojiAnimal() string
EmojiFood() string
EmojiPlant() string
EmojiMusic() string
EmojiVehicle() string
EmojiSport() string
EmojiFace() string
EmojiHand() string
EmojiClothing() string
EmojiLandmark() string
EmojiElectronics() string
EmojiGame() string
EmojiTools() string
EmojiWeather() string
EmojiJob() string
EmojiPerson() string
EmojiGesture() string
EmojiCostume() string
EmojiSentence() stringLanguage
Language() string
LanguageAbbreviation() string
LanguageBCP() string
ProgrammingLanguage() stringNumber
Number(min int, max int) int
Int() int
IntN(n int) int
Int8() int8
Int16() int16
Int32() int32
Int64() int64
IntRange(min, max int) int
Uint() uint
UintN(n uint) uint
Uint8() uint8
Uint16() uint16
Uint32() uint32
Uint64() uint64
UintRange(min, max uint) uint
Float32() float32
Float32Range(min, max float32) float32
Float64() float64
Float64Range(min, max float64) float64
ShuffleInts(a []int)
RandomInt(i []int) int
RandomUint(u []uint) uint
HexUint(bitsize int) stringString
Digit() string
DigitN(n uint) string
Letter() string
LetterN(n uint) string
Vowel() string
Lexify(str string) string
Numerify(str string) string
ShuffleStrings(a []string)
RandomString(a []string) stringCelebrity
CelebrityActor() string
CelebrityBusiness() string
CelebritySport() stringMinecraft
MinecraftOre() string
MinecraftWood() string
MinecraftArmorTier() string
MinecraftArmorPart() string
MinecraftWeapon() string
MinecraftTool() string
MinecraftDye() string
MinecraftFood() string
MinecraftAnimal() string
MinecraftVillagerJob() string
MinecraftVillagerStation() string
MinecraftVillagerLevel() string
MinecraftMobPassive() string
MinecraftMobNeutral() string
MinecraftMobHostile() string
MinecraftMobBoss() string
MinecraftBiome() string
MinecraftWeather() stringBook
Book() *BookInfo
BookTitle() string
BookAuthor() string
BookGenre() stringMovie
Movie() *MovieInfo
MovieName() string
MovieGenre() stringError
Error() error
ErrorObject() error
ErrorDatabase() error
ErrorGRPC() error
ErrorHTTP() error
ErrorHTTPClient() error
ErrorHTTPServer() error
ErrorRuntime() error
ErrorValidation() errorSchool
School() stringSong
Song() *SongInfo
SongName() string
SongArtist() string
SongGenre() stringOverview (`data/README.md`)
Gofakeit Data
Gofakeit data set
List
List()Get/Set/Remove Data
data.Get("desserts")
data.Set("desserts", map[string][]string{
"cake": {"chocolate", "vanilla"},
"pie": {"apple", "pecan"},
"ice cream": {"strawberry", "vanilla"},
})
data.Remove("desserts")Get/Set/Remove Sub Data
data.GetSubData("desserts", "cake")
data.SetSub("desserts", "cake", []string{"chocolate", "vanilla"})
data.RemoveSub("desserts", "cake")Overview (`source/README.md`)
Random Number Generators Collection
This repository contains a collection of random number generators (RNGs) implemented in Go, designed to cater to a wide range of applications, from cryptographic operations to testing environments. Each RNG in the collection offers distinct features and performance characteristics, making it suitable for various use cases, including those requiring cryptographic security.
Generators
Crypto
- Description: Utilizes Go's
crypto/randpackage to provide cryptographically secure random numbers, suitable for security-sensitive applications. - Usage:go
source := NewCryptoSource() number := source.Uint64()
JSF (Jenkins Small Fast)
- Description: An implementation of the Jenkins Small Fast hash function for efficient pseudo-random number generation, balancing speed and randomness quality for general use.
- Usage:go
source := NewJSFSource(seed) number := source.Uint64()
SFC (Simple Fast Counter)
- Description: Based on the Simple Fast Counter algorithm, this source offers rapid number generation with satisfactory randomness properties, ideal for simulations and non-cryptographic applications.
- Usage:go
source := NewSFCSource(seed) number := source.Uint64()
Dumb
- Description: A deterministic generator designed primarily for testing, providing predictable output for scenarios where consistent results are more beneficial than high-quality randomness.
- Usage:go
source := NewDumb(seed) number := source.Uint64()
Installation
To use these RNGs in your Go project, import the package as follows:
import "github.com/yourusername/randsource"Replace yourusername with your GitHub username or organization name where the repository is hosted.
Usage
After importing the package, initialize the desired RNG with or without a seed (as applicable) and use the Uint64 method to generate random numbers. See the usage examples under each generator's description for more details.
Benchmarks
Performance benchmarks for each RNG are provided to help you choose the right generator for your application. These benchmarks cover various aspects, including speed and randomness quality.
For detailed benchmark results, see the Benchmarks file.
Contributing
We welcome contributions and suggestions! Please open an issue or submit a pull request with your improvements.
Overview (`cmd/gofakeit/README.md`)
Gofakeit Command Line Tool
Run gofakeit via that command line.
All functions are available to run in lowercase and if they require additional parameters you may pass by space seperation.
Installation
go install -v github.com/brianvoe/gofakeit/v7/cmd/gofakeit@latestExample
gofakeit firstname // billy
gofakeit sentence 5 // Exercitationem occaecati sed dignissimos inventore.
gofakeit shufflestrings hello,world,whats,up // up,hello,whats,world
// You can also pass in a length flag to output a specific function multiple times
gofakeit sentence -loop=5List of available functions
gofakeit list
// You may also pass a category and/or function to get a specific function data
gofakeit list [category] [function]Overview (`cmd/gofakeitserver/README.md`)
Gofakeit Server
Run gofakeit via a running server.
All functions are available to run in lowercase as first path and if they take in additional parameters you may pass by query parameters.
Installation
go get -u github.com/brianvoe/gofakeit/v7/cmd/gofakeitserverExample
gofakeitserver // default port is 8080--- METRICS ---
- Files Extracted: 5
- Estimated Token Budget: ~5330 tokens
- Canonical Reference: https://codewiki.google/github.com/brianvoe/gofakeit