
Random data generator written in go
Thank you to all our Gofakeit contributors!
go get github.com/brianvoe/gofakeit/v7
import "github.com/brianvoe/gofakeit/v7"
gofakeit.Name() // Markus Moen
gofakeit.Email() // alaynawuckert@kozey.biz
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
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 want
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)
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)
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.
import "github.com/brianvoe/gofakeit/v7"
// Create structs with random injected data
type Foo struct {
Str string
Int int
Pointer *int
Name string `fake:"{firstname}"` // Any available function all lowercase
Sentence string `fake:"{sentence}"`
RandStr string `fake:"{randomstring:[hello,world]}"`
Number string `fake:"{number:1,10}"` // Comma separated for multiple values
Regex string `fake:"{regex:[abcdef]{5}}"` // Generate string from regex
Map map[string]int `fakesize:"2"`
Array []string `fakesize:"2"`
ArrayRange []string `fakesize:"2,6"`
Bar Bar
Skip *string `fake:"skip"` // Set to "skip" to not generate data for
SkipAlt *string `fake:"-"` // Set to "-" to not generate data for
Created time.Time // Can take in a fake tag as well as a format tag
CreatedFormat time.Time `fake:"{year}-{month}-{day}" format:"2006-01-02"`
}
type Bar struct {
Name string
Number int
Float float32
}
// Pass your struct as a pointer
var f Foo
err := gofakeit.Struct(&f)
fmt.Println(f.Str) // hrukpttuezptneuvunh
fmt.Println(f.Int) // -7825289004089916589
fmt.Println(*f.Pointer) // -343806609094473732
fmt.Println(f.Name) // fred
fmt.Println(f.Sentence) // Record river mind.
fmt.Println(f.RandStr) // world
fmt.Println(f.Number) // 4
fmt.Println(f.Regex) // cbdfc
fmt.Println(f.Map) // map[PxLIo:52 lxwnqhqc:846]
fmt.Println(f.Array) // cbdfc
fmt.Printf("%+v", f.Bar) // {Name:QFpZ Number:-2882647639396178786 Float:1.7636692e+37}
fmt.Println(f.Skip) // <nil>
fmt.Println(f.Created.String()) // 1908-12-07 04:14:25.685339029 +0000 UTC
// Supported formats
// int, int8, int16, int32, int64,
// uint, uint8, uint16, uint32, uint64,
// float32, float64,
// bool, string,
// array, pointers, map
// time.Time // If setting time you can also set a format tag
// Nested Struct Fields and Embedded Fields
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 UTC
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) // loredlowlh
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 RandomInt
Unavailable 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) any
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-7485
All functions also exist as methods on the Faker struct
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() string
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() string
UUID() string
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() *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
Contact() *ContactInfo
Email() string
Phone() string
PhoneFormatted() string
Teams(peopleArray []string, teamsArray []string) map[string][]string
Struct(v any)
Slice(v any)
Map() map[string]any
Generate(value string) string
Regex(value string) string
Username() string
Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string
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)
Gamertag() string
Dice(numDice uint, sides []uint) []uint
BeerAlcohol() string
BeerBlg() string
BeerHop() string
BeerIbu() string
BeerMalt() string
BeerName() string
BeerStyle() string
BeerYeast() string
$ claude mcp add gofakeit \
-- python -m otcore.mcp_server <graph>