gofakeit Documentation

Random fake data generator written in go

5,402 stars Go Go 5 files ยท ~5,410 tokens #data#fake#generator#go#golang#random#seed
RAW Doc

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

Contributors

Thank you to all our Gofakeit contributors!

Installation

go
go get github.com/brianvoe/gofakeit/v7

Simple Usage

go
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()       // USD

See full list of functions

Seed

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.

go
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 want

Random 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.

go
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.

go
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.

text
/* 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.

go
// 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 UTC

Custom 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.

go
// 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) // loredlowlh

Templates

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

go
- 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 RandomInt

Unavailable Gofakeit functions

go
// Any functions that dont have a return value
- AnythingThatReturnsVoid(): void

// Not available to use in templates
- Template(co *TemplateOptions) ([]byte, error)
- RandomMapKey(mapI any) any

Example Usages

go
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:

text
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-7485

Functions

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.

go
CSV(co *CSVOptions) ([]byte, error)
JSON(jo *JSONOptions) ([]byte, error)
XML(xo *XMLOptions) ([]byte, error)
FileExtension() string
FileMimeType() string

Template

Passing nil will auto generate data using default values.

go
Template(co *TemplateOptions) (string, error)
Markdown(co *MarkdownOptions) (string, error)
EmailText(co *EmailOptions) (string, error)
FixedWidth(co *FixedWidthOptions) (string, error)

ID

go
ID() string
UUID() string

Product

go
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) string

Person

go
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][]string

Generate

go
Struct(v any)
Slice(v any)
Map() map[string]any
Generate(value string) string
Regex(value string) string

Database

go
SQL(so *SQLOptions) (string, error)

Auth

go
Username() string
Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string

Address

go
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

go
AirlineAircraftType() string
AirlineAirplane() string
AirlineAirport() string
AirlineAirportIATA() string
AirlineFlightNumber() string
AirlineRecordLocator() string
AirlineSeat() string

Game

go
Gamertag() string
Dice(numDice uint, sides []uint) []uint

Beer

go
BeerAlcohol() string
BeerBlg() string
BeerHop() string
BeerIbu() string
BeerMalt() string
BeerName() string
BeerStyle() string
BeerYeast() string

Car

go
Car() *CarInfo
CarMaker() string
CarModel() string
CarType() string
CarFuelType() string
CarTransmissionType() string

Words

text
/* Detailed source-code truncated for AI context efficiency. */

Foods

go
Fruit() string
Vegetable() string
Breakfast() string
Lunch() string
Dinner() string
Snack() string
Dessert() string
Drink() string

Misc

go
Bool() bool
Weighted(options []any, weights []float32) (any, error)
FlipACoin() string
RandomMapKey(mapI any) any
ShuffleAnySlice(v any)

Colors

go
Color() string
HexColor() string
RGBColor() []int
HSLColor() []int
SafeColor() string
NiceColors() string

Images

go
Image(width int, height int) *img.RGBA
ImageJpeg(width int, height int) []byte
ImagePng(width int, height int) []byte

Internet

go
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() string

HTML

go
InputName() string
Svg(options *SVGOptions) string

Date/Time

go
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() string

Payment

go
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() string

Finance

go
Cusip() string
Isin() string

Company

go
BS() string
Blurb() string
BuzzWord() string
Company() string
CompanySuffix() string
Job() *JobInfo
JobDescriptor() string
JobLevel() string
JobTitle() string
Slogan() string

Hacker

go
HackerAbbreviation() string
HackerAdjective() string
HackeringVerb() string
HackerNoun() string
HackerPhrase() string
HackerVerb() string

Hipster

go
HipsterWord() string
HipsterSentence() string
HipsterParagraph() string

App

go
AppName() string
AppVersion() string
AppAuthor() string

Animal

go
PetName() string
Animal() string
AnimalType() string
FarmAnimal() string
Cat() string
Dog() string
Bird() string

Emoji

go
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() string

Language

go
Language() string
LanguageAbbreviation() string
LanguageBCP() string
ProgrammingLanguage() string

Number

go
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) string

String

go
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) string

Celebrity

go
CelebrityActor() string
CelebrityBusiness() string
CelebritySport() string

Minecraft

go
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() string

Book

go
Book() *BookInfo
BookTitle() string
BookAuthor() string
BookGenre() string

Movie

go
Movie() *MovieInfo
MovieName() string
MovieGenre() string

Error

go
Error() error
ErrorObject() error
ErrorDatabase() error
ErrorGRPC() error
ErrorHTTP() error
ErrorHTTPClient() error
ErrorHTTPServer() error
ErrorRuntime() error
ErrorValidation() error

School

go
School() string

Song

go
Song() *SongInfo
SongName() string
SongArtist() string
SongGenre() string

Overview (`data/README.md`)

Gofakeit Data

Gofakeit data set

List

go
List()

Get/Set/Remove Data

go
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

go
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/rand package 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:

go
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
go install -v github.com/brianvoe/gofakeit/v7/cmd/gofakeit@latest

Example

bash
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=5

List of available functions

bash
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
go get -u github.com/brianvoe/gofakeit/v7/cmd/gofakeitserver

Example

bash
gofakeitserver // default port is 8080

--- METRICS ---