Documentation ¶
Overview ¶
Example (CustomFaker) ¶
You can also add your own generator function to your own defined tags.
package main import ( "fmt" "reflect" "github.com/bxcodec/faker/v3" ) // Gondoruwo ... type Gondoruwo struct { Name string Locatadata int } // custom type that aliases over slice of byte type CustomUUID []byte // Sample ... type Sample struct { ID int64 `faker:"customIdFaker"` Gondoruwo Gondoruwo `faker:"gondoruwo"` Danger string `faker:"danger"` UUID CustomUUID `faker:"customUUID"` } // CustomGenerator ... func CustomGenerator() { _ = faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) { return int64(43), nil }) _ = faker.AddProvider("danger", func(v reflect.Value) (interface{}, error) { return "danger-ranger", nil }) _ = faker.AddProvider("gondoruwo", func(v reflect.Value) (interface{}, error) { obj := Gondoruwo{ Name: "Power", Locatadata: 324, } return obj, nil }) _ = faker.AddProvider("customUUID", func(v reflect.Value) (interface{}, error) { s := CustomUUID{ 0, 8, 7, 2, 3, } return s, nil }) } // You can also add your own generator function to your own defined tags. func main() { CustomGenerator() var sample Sample _ = faker.FakeData(&sample) fmt.Printf("%+v", sample) }
Output: {ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger UUID:[0 8 7 2 3]}
Example (SingleFakeData) ¶
Single fake function can be used for retrieving particular values.
// Address faker.Latitude() // => 81.12195 faker.Longitude() // => -84.38158 // Datetime faker.UnixTime() // => 1197930901 faker.Date() // => 1982-02-27 faker.TimeString() // => 03:10:25 faker.MonthName() // => February faker.YearString() // => 1994 faker.DayOfWeek() // => Sunday faker.DayOfMonth() // => 20 faker.Timestamp() // => 1973-06-21 14:50:46 faker.Century() // => IV faker.Timezone() // => Asia/Jakarta faker.Timeperiod() // => PM // Internet faker.Email() // => mJBJtbv@OSAaT.com faker.MacAddress() // => cd:65:e1:d4:76:c6 faker.DomainName() // => FWZcaRE.org faker.URL() // => https://www.oEuqqAY.org/QgqfOhd faker.Username() // => lVxELHS faker.IPv4() // => 99.23.42.63 faker.IPv6() // => 975c:fb2c:2133:fbdd:beda:282e:1e0a:ec7d faker.Password() // => dfJdyHGuVkHBgnHLQQgpINApynzexnRpgIKBpiIjpTP // Words and Sentences faker.Word() // => nesciunt faker.Sentence() // => Consequatur perferendis voluptatem accusantium. faker.Paragraph() // => Aut consequatur sit perferendis accusantium voluptatem. Accusantium perferendis consequatur voluptatem sit aut. Aut sit accusantium consequatur voluptatem perferendis. Perferendis voluptatem aut accusantium consequatur sit. // Payment faker.CCType() // => American Express faker.CCNumber() // => 373641309057568 faker.Currency() // => USD faker.AmountWithCurrency() // => USD 49257.100 // Person faker.TitleMale() // => Mr. faker.TitleFemale() // => Mrs. faker.FirstName() // => Whitney faker.FirstNameMale() // => Kenny faker.FirstNameFemale() // => Jana faker.LastName() // => Rohan faker.Name() // => Mrs. Casandra Kiehn // Phone faker.Phonenumber() // -> 201-886-0269 faker.TollFreePhoneNumber() // => (777) 831-964572 faker.E164PhoneNumber() // => +724891571063 // UUID faker.UUIDHyphenated() // => 8f8e4463-9560-4a38-9b0c-ef24481e4e27 faker.UUIDDigit() // => 90ea6479fd0e4940af741f0a87596b73 // Unique values faker.SetGenerateUniqueValues(true) // Enable unique data generation on single fake data functions faker.Word() // ... faker.SetGenerateUniqueValues(false) // Disable unique data generation on single fake data functions faker.ResetUnique() // Forget all generated unique values
Output:
Example (WithTags) ¶
package main import ( "fmt" "github.com/bxcodec/faker/v3" ) // SomeStructWithTags ... type SomeStructWithTags struct { Latitude float32 `faker:"lat"` Longitude float32 `faker:"long"` CreditCardNumber string `faker:"cc_number"` CreditCardType string `faker:"cc_type"` Email string `faker:"email"` DomainName string `faker:"domain_name"` IPV4 string `faker:"ipv4"` IPV6 string `faker:"ipv6"` Password string `faker:"password"` Jwt string `faker:"jwt"` PhoneNumber string `faker:"phone_number"` MacAddress string `faker:"mac_address"` URL string `faker:"url"` UserName string `faker:"username"` TollFreeNumber string `faker:"toll_free_number"` E164PhoneNumber string `faker:"e_164_phone_number"` TitleMale string `faker:"title_male"` TitleFemale string `faker:"title_female"` FirstName string `faker:"first_name"` FirstNameMale string `faker:"first_name_male"` FirstNameFemale string `faker:"first_name_female"` LastName string `faker:"last_name"` Name string `faker:"name"` UnixTime int64 `faker:"unix_time"` Date string `faker:"date"` Time string `faker:"time"` MonthName string `faker:"month_name"` Year string `faker:"year"` DayOfWeek string `faker:"day_of_week"` DayOfMonth string `faker:"day_of_month"` Timestamp string `faker:"timestamp"` Century string `faker:"century"` TimeZone string `faker:"timezone"` TimePeriod string `faker:"time_period"` Word string `faker:"word"` Sentence string `faker:"sentence"` Paragraph string `faker:"paragraph"` Currency string `faker:"currency"` Amount float64 `faker:"amount"` AmountWithCurrency string `faker:"amount_with_currency"` UUIDHypenated string `faker:"uuid_hyphenated"` UUID string `faker:"uuid_digit"` Skip string `faker:"-"` PaymentMethod string `faker:"oneof: cc, paypal, check, money order"` // oneof will randomly pick one of the comma-separated values supplied in the tag AccountID int `faker:"oneof: 15, 27, 61"` // use commas to separate the values for now. Future support for other separator characters may be added Price32 float32 `faker:"oneof: 4.95, 9.99, 31997.97"` Price64 float64 `faker:"oneof: 47463.9463525, 993747.95662529, 11131997.978767990"` NumS64 int64 `faker:"oneof: 1, 2"` NumS32 int32 `faker:"oneof: -3, 4"` NumS16 int16 `faker:"oneof: -5, 6"` NumS8 int8 `faker:"oneof: 7, -8"` NumU64 uint64 `faker:"oneof: 9, 10"` NumU32 uint32 `faker:"oneof: 11, 12"` NumU16 uint16 `faker:"oneof: 13, 14"` NumU8 uint8 `faker:"oneof: 15, 16"` NumU uint `faker:"oneof: 17, 18"` } func main() { a := SomeStructWithTags{} err := faker.FakeData(&a) if err != nil { fmt.Println(err) } fmt.Printf("%+v", a) /* Result: { Latitude: 81.12195 Longitude: -84.38158 CreditCardType: American Express CreditCardNumber: 373641309057568 Email: mJBJtbv@OSAaT.ru DomainName: FWZcaRE.ru, IPV4: 99.23.42.63 IPV6: 975c:fb2c:2133:fbdd:beda:282e:1e0a:ec7d Password: dfJdyHGuVkHBgnHLQQgpINApynzexnRpgIKBpiIjpTPOmNyMFb Jwt: HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR.HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR.HDMNSOKhEIYkPIuHcVjfCtHlKkaqLGrUEqjKVkgR PhoneNumber: 792-153-4861 MacAddress: cd:65:e1:d4:76:c6 URL: https://www.oEuqqAY.org/QgqfOhd UserName: lVxELHS TollFreeNumber: (777) 831-964572 E164PhoneNumber: +724891571063 TitleMale: Mr. TitleFemale: Queen FirstName: Whitney FirstNameMale: Kenny FirstNameFemale: Jana LastName: Rohan Name: Miss Casandra Kiehn UnixTime: 1197930901 Date: 1982-02-27 Time: 03:10:25 MonthName: February Year: 1996 DayOfWeek: Sunday DayOfMonth: 20 Timestamp: 1973-06-21 14:50:46 Century: IV TimeZone: Canada/Eastern TimePeriod: AM Word: nesciunt Sentence: Consequatur perferendis aut sit voluptatem accusantium. Paragraph: Aut consequatur sit perferendis accusantium voluptatem. Accusantium perferendis consequatur voluptatem sit aut. Aut sit accusantium consequatur voluptatem perferendis. Perferendis voluptatem aut accusantium consequatur sit. Currency: IRR, Amount: 88.990000, AmountWithCurrency: XBB 49257.100000, UUIDHypenated: 8f8e4463-9560-4a38-9b0c-ef24481e4e27, UUID: 90ea6479fd0e4940af741f0a87596b73, PaymentMethod: paypal, AccountID: 61, Price32: 4.95, Price64: 993747.95662529 NumS64: 1 NumS32: -3 NumS16: 5 NumS8: -8 NumU64: 9 NumU32: 11 NumU16: 13 NumU8: 15 NumU: 17 Skip: } */ }
Output:
Example (WithTagsAndUnique) ¶
package main import ( "fmt" "github.com/bxcodec/faker/v3" ) // SomeStructWithUnique ... type SomeStructWithUnique struct { Word string `faker:"word,unique"` } func main() { for i := 0; i < 5; i++ { // Generate 5 structs having a unique word a := SomeStructWithUnique{} err := faker.FakeData(&a) if err != nil { fmt.Println(err) } fmt.Printf("%+v", a) } faker.ResetUnique() // Forget all generated unique values. Allows to start generating another unrelated dataset. // Result: // {Word:nobis}{Word:recusandae}{Word:praesentium}{Word:doloremque}{Word:non} }
Output:
Example (WithTagsLang) ¶
You can set length for your random strings also set boundary for your integers.
// SomeStruct ... type SomeStruct struct { StringENG string `faker:"lang=eng"` StringCHI string `faker:"lang=chi"` StringRUS string `faker:"lang=rus"` StringJPN string `faker:"lang=jpn"` StringKOR string `faker:"lang=kor"` StringEMJ string `faker:"lang=emj"` } a := SomeStruct{} _ = faker.SetRandomStringLength(5) _ = faker.FakeData(&a) fmt.Printf("%+v", a) // Result: /* { StringENG:VVcaPS StringCHI: 随机字符串 StringRUS:ваЩфз StringJPN:びゃほぱヒてふ StringKOR:텻밚쨋큊몉 StringEMJ:🐅😄🕢🍪🐡 } */
Output:
Example (WithTagsLengthAndBoundary) ¶
You can set length for your random strings also set boundary for your integers.
// SomeStruct ... type SomeStruct struct { Inta int `faker:"boundary_start=5, boundary_end=10"` Int8 int8 `faker:"boundary_start=100, boundary_end=1000"` Int16 int16 `faker:"boundary_start=123, boundary_end=1123"` Int32 int32 `faker:"boundary_start=-10, boundary_end=8123"` Int64 int64 `faker:"boundary_start=31, boundary_end=88"` UInta uint `faker:"boundary_start=35, boundary_end=152"` UInt8 uint8 `faker:"boundary_start=5, boundary_end=1425"` UInt16 uint16 `faker:"boundary_start=245, boundary_end=2125"` UInt32 uint32 `faker:"boundary_start=0, boundary_end=40"` UInt64 uint64 `faker:"boundary_start=14, boundary_end=50"` Float32 float32 `faker:"boundary_start=12.65, boundary_end=184.05"` Float64 float64 `faker:"boundary_start=1.256, boundary_end=3.4"` ASString []string `faker:"len=50"` SString string `faker:"len=25"` MSString map[string]string `faker:"len=30"` MIint map[int]int `faker:"boundary_start=5, boundary_end=10"` } _ = faker.SetRandomMapAndSliceSize(20) // Random generated map or array size wont exceed 20... a := SomeStruct{} _ = faker.FakeData(&a) fmt.Printf("%+v", a) // Result: /* { Inta:7 Int8:-102 Int16:556 Int32:113 Int64:70 UInta:78 UInt8:54 UInt16:1797 UInt32:8 UInt64:34 Float32:60.999058 Float64:2.590148738554016 ASString:[ geHYIpEoQhQdijFooVEAOyvtTwJOofbQPJdbHvEEdjueZaKIgI WVJBBtmrrVccyIydAiLSkMwWbFzFMEotEXsyUXqcmBTVORlkJK xYiRTRSZRuGDcMWYoPALVMZgIXoTQtmdGXQfbISKJiavLspuBV qsoiYlyRbXLDAMoIdQhgMriODYWCTEYepmjaldWLLjkulDGuQN GQXUlqNkVjPKodMebPIeoZZlxfhbQJOjHSRjUTrcgBFPeDZIxn MEeRkkLceDsqKLEJFEjJxHtYrYxQMxYcuRHEDGYSPbELDQLSsj tWUIACjQWeiUhbboGuuEQIhUJCRSBzVImpYwOlFbsjCRmxboZW ZDaAUZEgFKbMJoKIMpymTreeZGWLXNCfVzaEyWNdbkaZOcsfst uwlsZBMlEknIBsALpXRaplZWVtXTKzsWglRVBpmfsQfqraiEYA AXszbzsOzYPYeXHXRwoPmoPoBxopdFFvWMBTPCxESTepRpjlnB kTuOPHlUrSzUQRmZMYplWbyoBbWzQYCiydyzurOduhjuyiGrCE FZbeLMbelIeCMnixknIARZRbwALObGXADQqianJbkiEAqqpdnK TiQrZbnkvxEciyKXlliUDOGVdpMoAsHSalFbLcYyXxNFLAhqjy KlbjbloxkWKSqvUfJQPpFLoddWgeABfYUoaAnylKmEHwxgNsnO ] SString:VVcaPSFrOPYlEkpVyTRbSZneB MSString:map[ ueFBFTTmqDwrXDoXAYTRhQRmLXhudA:AhQewvZfrlytbAROzGjpXUmNQzIoGl fZwrCsFfZwqMsDJXOUYIacflFIeyFU:VMufFCRRHTtuFthOrRAMbzbKVJHnvJ rHDQTyZqZVSPLwTtZfNSwKWrgmRghL:lRSXNHkhUyjDuBgoAfrQwOcHYilqRB BvCpQJMHzKXKbOoAnTXkLCNxKshwWr:tiNFrXAXUtdywkyygWBrEVrmAcAepD uWWKgHKTkUgAZiopAIUmgVWrkrceVy:GuuDNTUiaBtOKwWrMoZDiyaOPxywnq HohMjOdMDkAqimKPTgdjUorydpKkly:whAjmraukcZczskqycoJELlMJTghca umEgMBGUvBptdKImKsoWXMGJJoRbgT:tPpgHgLEyHmDOocOiSgTbXQHVduLxP SRQLHjBXCXKvbLIktdKeLwMnIFOmbi:IJBpLyTcraOxOUtwSKTisjElpulkTL dbnDeJZLqMXQGjbTSNxPSlfDHGCghU:JWrymovFwNWbIQBxPpQmlgJsgpXcui roraKNGnBXnrJlsxTnFgxHyZeTXdAC:XIcLWqUAQAbfkRrgfjrTVxZCvRJXyl TrvxqVVjXAboYDPvUglSJQrltPjzLx:nBhWdfNPybnNnCyQlSshWKOnwUMQzL dTHhWJWMwfVvKpIKTFCaoBJgKmnfbD:ixjNHsvSkRkFiNLpgUzIKPsheqhCeY lWyBrtfcGWiNbSTJZJXwOPvVngZZMk:kvlYeGgwguVtiafGKjHWsYWewbaXte bigsYNfVcNMGtnzgaqEjeRRlIcUdbR:hYOnJupEOvblTTEYzZYPuTVmvTmiit ] MIint:map[7:7 5:7 8:8 9:5 6:5] } */
Output:
Example (WithTagsSliceLength) ¶
You can set the size for your random slices.
// SomeStruct ... type SomeStruct struct { EmptyList []string `faker:"slice_len=0"` FixedStringList []string `faker:"slice_len=2"` FixedIntList []int64 `faker:"slice_len=4"` RandomIntList []int64 } _ = faker.SetRandomMapAndSliceSize(20) // If no slice_len is set, this sets the max of the random size a := SomeStruct{} _ = faker.FakeData(&a) fmt.Printf("%+v", a) // Result: /* { EmptyList:[] FixedStringList:[ geHYIpEoQhQdijFooVEAOyvtTwJOofbQPJdbHvEEdjueZaKIgI WVJBBtmrrVccyIydAiLSkMwWbFzFMEotEXsyUXqcmBTVORlkJK ] FixedIntList:[10,25,60,15] RandomIntList:[5,16,134,6235,123,53,123] //Random len() with a max of 20 } */
Output:
Example (WithoutTag) ¶
You also can use faker to generate your structs data randomly without any tag. And it will fill the data based on its data-type.
package main import ( "fmt" "github.com/bxcodec/faker/v3" ) // SomeStruct ... type SomeStruct struct { Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 String string Bool bool SString []string SInt []int SInt8 []int8 SInt16 []int16 SInt32 []int32 SInt64 []int64 SFloat32 []float32 SFloat64 []float64 SBool []bool Struct AStruct } // AStruct ... type AStruct struct { Number int64 Height int64 AnotherStruct BStruct } // BStruct ... type BStruct struct { Image string } // You also can use faker to generate your structs data randomly without any tag. // And it will fill the data based on its data-type. func main() { a := SomeStruct{} err := faker.FakeData(&a) if err != nil { fmt.Println(err) } fmt.Printf("%+v", a) /* Result: { Int:5231564546548329 Int8:52 Int16:8 Int32:2046951236 Int64:1486554863682234423 String:ELIQhSfhHmWxyzRPOTNblEQsp Bool:false SString:[bzYwplRGUAXPwatnpVMWSYjep zmeuJVGHHgmIsuyWmLJnDmbTI FqtejCwoDyMBWatoykIzorCJZ] SInt:[11661230973193 626062851427 12674621422454 5566279673347] SInt8:[12 2 58 22 11 66 5 88] SInt16:[29295225 8411281 69902706328] SInt32:[60525685140 2733640366211 278043484637 5167734561481] SInt64:[81684520429188374184 9917955420365482658170 996818723778286568 163646873275501565] SFloat32:[0.556428 0.7692596 0.6779895 0.29171365 0.95445055] SFloat64:[0.44829454895586585 0.5495675898536803 0.6584538253883265] SBool:[true false true false true true false] Struct:{ Number:1 Height:26 AnotherStruct:{ Image:RmmaaHkAkrWHldVbBNuQSKlRb } } } */ }
Output:
Index ¶
- Constants
- Variables
- func AddProvider(tag string, provider TaggedFunction) error
- func AmountWithCurrency() string
- func CCNumber() string
- func CCType() string
- func Century() string
- func ChineseFirstName() string
- func ChineseLastName() string
- func ChineseName() string
- func Currency() string
- func Date() string
- func DayOfMonth() string
- func DayOfWeek() string
- func DomainName() string
- func E164PhoneNumber() string
- func Email() string
- func FakeData(a interface{}) error
- func FirstName() string
- func FirstNameFemale() string
- func FirstNameMale() string
- func Gender() string
- func IPv4() string
- func IPv6() string
- func Jwt() string
- func LastName() string
- func Latitude() float64
- func Longitude() float64
- func MacAddress() string
- func MonthName() string
- func Name() string
- func NewSafeSource(in mathrand.Source) mathrand.Source
- func Paragraph() string
- func Password() string
- func Phonenumber() string
- func RandomInt(parameters ...int) (p []int, err error)
- func RandomUnixTime() int64
- func RemoveProvider(tag string) error
- func ResetUnique()
- func Sentence() string
- func SetAddress(net Addresser)
- func SetCryptoSource(in io.Reader)
- func SetDataFaker(d DataFaker)
- func SetDateTimer(d DateTimer)
- func SetDowser(d Dowser)
- func SetGenerateUniqueValues(unique bool)
- func SetIgnoreInterface(ignore bool)
- func SetNetwork(net Networker)
- func SetNilIfLenIsZero(setNil bool)
- func SetPayment(p Render)
- func SetPhoner(p Phoner)
- func SetPrice(p Money)
- func SetRandomMapAndSliceMaxSize(size int) error
- func SetRandomMapAndSliceMinSize(size int) error
- func SetRandomMapAndSliceSize(size int) error
- func SetRandomNumberBoundaries(start, end int) error
- func SetRandomSource(in mathrand.Source)
- func SetRandomStringLength(size int) error
- func SetStringLang(l langRuneBoundary)
- func TimeString() string
- func Timeperiod() string
- func Timestamp() string
- func Timezone() string
- func TitleFemale() string
- func TitleMale() string
- func TollFreePhoneNumber() string
- func URL() string
- func UUIDDigit() string
- func UUIDHyphenated() string
- func UnixTime() int64
- func Username() string
- func Word() string
- func YearString() string
- type Address
- type Addresser
- type DataFaker
- type DateTime
- func (d DateTime) Century(v reflect.Value) (interface{}, error)
- func (d DateTime) Date(v reflect.Value) (interface{}, error)
- func (d DateTime) DayOfMonth(v reflect.Value) (interface{}, error)
- func (d DateTime) DayOfWeek(v reflect.Value) (interface{}, error)
- func (d DateTime) MonthName(v reflect.Value) (interface{}, error)
- func (d DateTime) Time(v reflect.Value) (interface{}, error)
- func (d DateTime) TimePeriod(v reflect.Value) (interface{}, error)
- func (d DateTime) TimeZone(v reflect.Value) (interface{}, error)
- func (d DateTime) Timestamp(v reflect.Value) (interface{}, error)
- func (d DateTime) UnixTime(v reflect.Value) (interface{}, error)
- func (d DateTime) Year(v reflect.Value) (interface{}, error)
- type DateTimer
- type Dowser
- type Identifier
- type Internet
- func (internet Internet) DomainName(v reflect.Value) (interface{}, error)
- func (internet Internet) Email(v reflect.Value) (interface{}, error)
- func (internet Internet) IPv4(v reflect.Value) (interface{}, error)
- func (internet Internet) IPv6(v reflect.Value) (interface{}, error)
- func (internet Internet) Jwt(v reflect.Value) (interface{}, error)
- func (internet Internet) MacAddress(v reflect.Value) (interface{}, error)
- func (internet Internet) Password(v reflect.Value) (interface{}, error)
- func (internet Internet) URL(v reflect.Value) (interface{}, error)
- func (internet Internet) UserName(v reflect.Value) (interface{}, error)
- type Lorem
- type Money
- type Networker
- type Payment
- type Person
- func (p Person) ChineseFirstName(v reflect.Value) (interface{}, error)
- func (p Person) ChineseLastName(v reflect.Value) (interface{}, error)
- func (p Person) ChineseName(v reflect.Value) (interface{}, error)
- func (p Person) FirstName(v reflect.Value) (interface{}, error)
- func (p Person) FirstNameFemale(v reflect.Value) (interface{}, error)
- func (p Person) FirstNameMale(v reflect.Value) (interface{}, error)
- func (p Person) Gender(v reflect.Value) (interface{}, error)
- func (p Person) LastName(v reflect.Value) (interface{}, error)
- func (p Person) Name(v reflect.Value) (interface{}, error)
- func (p Person) TitleFeMale(v reflect.Value) (interface{}, error)
- func (p Person) TitleMale(v reflect.Value) (interface{}, error)
- type Phone
- type Phoner
- type Price
- type Render
- type TaggedFunction
- type UUID
Examples ¶
Constants ¶
const ( BaseDateFormat = "2006-01-02" TimeFormat = "15:04:05" MonthFormat = "January" YearFormat = "2006" DayFormat = "Monday" DayOfMonthFormat = "_2" TimePeriodFormat = "PM" )
These example values must use the reference time "Mon Jan 2 15:04:05 MST 2006" as described at https://gobyexample.com/time-formatting-parsing
const ( ID = "uuid_digit" HyphenatedID = "uuid_hyphenated" EmailTag = "email" MacAddressTag = "mac_address" DomainNameTag = "domain_name" UserNameTag = "username" URLTag = "url" IPV4Tag = "ipv4" IPV6Tag = "ipv6" PASSWORD = "password" JWT = "jwt" LATITUDE = "lat" LONGITUDE = "long" CreditCardNumber = "cc_number" CreditCardType = "cc_type" PhoneNumber = "phone_number" TollFreeNumber = "toll_free_number" E164PhoneNumberTag = "e_164_phone_number" TitleMaleTag = "title_male" TitleFemaleTag = "title_female" FirstNameTag = "first_name" FirstNameMaleTag = "first_name_male" FirstNameFemaleTag = "first_name_female" LastNameTag = "last_name" NAME = "name" ChineseFirstNameTag = "chinese_first_name" ChineseLastNameTag = "chinese_last_name" ChineseNameTag = "chinese_name" GENDER = "gender" UnixTimeTag = "unix_time" DATE = "date" TIME = "time" MonthNameTag = "month_name" YEAR = "year" DayOfWeekTag = "day_of_week" DayOfMonthTag = "day_of_month" TIMESTAMP = "timestamp" CENTURY = "century" TIMEZONE = "timezone" TimePeriodTag = "time_period" WORD = "word" SENTENCE = "sentence" PARAGRAPH = "paragraph" CurrencyTag = "currency" AmountTag = "amount" AmountWithCurrencyTag = "amount_with_currency" SKIP = "-" Length = "len" SliceLength = "slice_len" Language = "lang" BoundaryStart = "boundary_start" BoundaryEnd = "boundary_end" Equals = "=" ONEOF = "oneof" )
Supported tags
Variables ¶
var ( // LangENG is for english language LangENG = langRuneBoundary{65, 122, []rune{91, 92, 93, 94, 95, 96}} // LangCHI is for chinese language LangCHI = langRuneBoundary{19968, 40869, nil} // LangRUS is for russian language LangRUS = langRuneBoundary{1025, 1105, nil} // LangJPN is for japanese Hiragana Katakana language LangJPN = langRuneBoundary{12353, 12534, []rune{12436, 12437, 12438, 12439, 12440, 12441, 12442, 12443, 12444, 12445, 12446, 12447, 12448}} // LangKOR is for korean Hangul language LangKOR = langRuneBoundary{44032, 55203, nil} // EmotEMJ is for emoticons EmotEMJ = langRuneBoundary{126976, 129535, nil} )
Language rune boundaries here
var ( ErrUnsupportedKindPtr = "Unsupported kind: %s Change Without using * (pointer) in Field of %s" ErrUnsupportedKind = "Unsupported kind: %s" ErrValueNotPtr = "Not a pointer value" ErrTagNotSupported = "Tag unsupported: %s" ErrTagAlreadyExists = "Tag exists" ErrTagDoesNotExist = "Tag does not exist" ErrMoreArguments = "Passed more arguments than is possible : (%d)" ErrNotSupportedPointer = "Use sample:=new(%s)\n faker.FakeData(sample) instead" ErrSmallerThanZero = "Size:%d is smaller than zero." ErrSmallerThanOne = "Size:%d is smaller than one." ErrUniqueFailure = "Failed to generate a unique value for field \"%s\"" ErrStartValueBiggerThanEnd = "Start value can not be bigger than end value." ErrWrongFormattedTag = "Tag \"%s\" is not written properly" ErrUnknownType = "Unknown Type" ErrNotSupportedTypeForTag = "Type is not supported by tag." ErrUnsupportedTagArguments = "Tag arguments are not compatible with field type." ErrDuplicateSeparator = "Duplicate separator for tag arguments." ErrNotEnoughTagArguments = "Not enough arguments for tag." ErrUnsupportedNumberType = "Unsupported Number type." )
Generic Error Messages for tags
ErrUnsupportedKindPtr: Error when get fake from ptr ErrUnsupportedKind: Error on passing unsupported kind ErrValueNotPtr: Error when value is not pointer ErrTagNotSupported: Error when tag is not supported ErrTagAlreadyExists: Error when tag exists and call AddProvider ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider ErrMoreArguments: Error on passing more arguments ErrNotSupportedPointer: Error when passing unsupported pointer
var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag, IPV6Tag, PASSWORD, JWT, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber, E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag, NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag, YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH, CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, }
PriorityTags define the priority order of the tag
Functions ¶
func AddProvider ¶
func AddProvider(tag string, provider TaggedFunction) error
AddProvider extend faker with tag to generate fake data with specified custom algorithm Example:
type Gondoruwo struct { Name string Locatadata int } type Sample struct { ID int64 `faker:"customIdFaker"` Gondoruwo Gondoruwo `faker:"gondoruwo"` Danger string `faker:"danger"` } func CustomGenerator() { // explicit faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) { return int64(43), nil }) // functional faker.AddProvider("danger", func() faker.TaggedFunction { return func(v reflect.Value) (interface{}, error) { return "danger-ranger", nil } }()) faker.AddProvider("gondoruwo", func(v reflect.Value) (interface{}, error) { obj := Gondoruwo{ Name: "Power", Locatadata: 324, } return obj, nil }) } func main() { CustomGenerator() var sample Sample faker.FakeData(&sample) fmt.Printf("%+v", sample) }
Will print
{ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger}
Notes: when using a custom provider make sure to return the same type as the field
func AmountWithCurrency ¶
func AmountWithCurrency() string
AmountWithCurrency get fake AmountWithCurrency USD 49257.100
func CCNumber ¶
func CCNumber() string
CCNumber get a credit card number randomly in string (VISA, MasterCard, etc)
func CCType ¶
func CCType() string
CCType get a credit card type randomly in string (VISA, MasterCard, etc)
func ChineseFirstName ¶ added in v3.8.0
func ChineseFirstName() string
ChineseFirstName get chinese first name
func ChineseLastName ¶ added in v3.8.0
func ChineseLastName() string
ChineseLastName get chinese lsst name
func FakeData ¶
func FakeData(a interface{}) error
FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data. You don't need to Create your own data for your testing.
func NewSafeSource ¶ added in v3.7.0
NewSafeSource wraps an unsafe rand.Source with a mutex to guard the random source against concurrent access.
func RandomInt ¶
RandomInt Get three parameters , only first mandatory and the rest are optional (minimum_int, maximum_int, count)
If only set one parameter : An integer greater than minimum_int will be returned If only set two parameters : All integers between minimum_int and maximum_int will be returned, in a random order. If three parameters: `count` integers between minimum_int and maximum_int will be returned.
func RandomUnixTime ¶
func RandomUnixTime() int64
RandomUnixTime is a helper function returning random Unix time
func RemoveProvider ¶ added in v3.6.0
RemoveProvider removes existing customization added with AddProvider
func ResetUnique ¶ added in v3.2.0
func ResetUnique()
ResetUnique is used to forget generated unique values. Call this when you're done generating a dataset.
func SetCryptoSource ¶ added in v3.7.0
SetCryptoSource sets a new reader for functions using a cryptographically-safe random generator (e.g. UUID).
The default is the global source provided by crypto/rand.
func SetGenerateUniqueValues ¶ added in v3.2.0
func SetGenerateUniqueValues(unique bool)
SetGenerateUniqueValues allows to set the single fake data generator functions to generate unique data.
func SetIgnoreInterface ¶ added in v3.6.0
func SetIgnoreInterface(ignore bool)
SetIgnoreInterface allows to set a flag to ignore found interface{}s.
func SetNilIfLenIsZero ¶
func SetNilIfLenIsZero(setNil bool)
SetNilIfLenIsZero allows to set nil for the slice and maps, if size is 0.
func SetRandomMapAndSliceMaxSize ¶ added in v3.8.0
SetRandomMapAndSliceMaxSize sets the max size for maps and slices for random generation.
func SetRandomMapAndSliceMinSize ¶ added in v3.8.0
SetRandomMapAndSliceMinSize sets the min size for maps and slices for random generation.
func SetRandomMapAndSliceSize ¶
SetRandomMapAndSliceSize sets the size for maps and slices for random generation. deprecates, currently left for old version usage
func SetRandomNumberBoundaries ¶
SetRandomNumberBoundaries sets boundary for random number generation
func SetRandomSource ¶ added in v3.7.0
SetRandomSource sets a new random source at the package level.
To use a concurrent-safe source, you may wrap it with NewSafeSource, e.g. SetRandomSource(NewSafeSource(mysource)).
The default is the global, concurrent-safe source provided by math/rand.
func SetRandomStringLength ¶
SetRandomStringLength sets a length for random string generation
func SetStringLang ¶ added in v3.4.0
func SetStringLang(l langRuneBoundary)
SetStringLang sets language of random string generation (LangENG, LangCHI, LangRUS, LangJPN, LangKOR, EmotEMJ)
func Timestamp ¶
func Timestamp() string
Timestamp get timestamp randomly in string format: 2006-01-02 15:04:05
func TitleFemale ¶
func TitleFemale() string
TitleFemale get a title female randomly in string ("Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess")
func TitleMale ¶
func TitleMale() string
TitleMale get a title male randomly in string ("Mr.", "Dr.", "Prof.", "Lord", "King", "Prince")
func TollFreePhoneNumber ¶
func TollFreePhoneNumber() string
TollFreePhoneNumber get fake TollFreePhoneNumber
Types ¶
type Address ¶
type Address struct{}
Address struct
type Addresser ¶
type Addresser interface { Latitude(v reflect.Value) (interface{}, error) Longitude(v reflect.Value) (interface{}, error) }
Addresser is logical layer for Address
func GetAddress ¶
func GetAddress() Addresser
GetAddress returns a new Addresser interface of Address
type DataFaker ¶
type DataFaker interface { Word(v reflect.Value) (interface{}, error) Sentence(v reflect.Value) (interface{}, error) Paragraph(v reflect.Value) (interface{}, error) }
DataFaker generates randomized Words, Sentences and Paragraphs
type DateTime ¶
type DateTime struct { }
DateTime struct
func (DateTime) DayOfMonth ¶
DayOfMonth formats DateTime using example DayOfMonth const
func (DateTime) TimePeriod ¶
TimePeriod formats DateTime using example TimePeriod const
type DateTimer ¶
type DateTimer interface { UnixTime(v reflect.Value) (interface{}, error) Date(v reflect.Value) (interface{}, error) Time(v reflect.Value) (interface{}, error) MonthName(v reflect.Value) (interface{}, error) Year(v reflect.Value) (interface{}, error) DayOfWeek(v reflect.Value) (interface{}, error) DayOfMonth(v reflect.Value) (interface{}, error) Timestamp(v reflect.Value) (interface{}, error) Century(v reflect.Value) (interface{}, error) TimeZone(v reflect.Value) (interface{}, error) TimePeriod(v reflect.Value) (interface{}, error) }
A DateTimer contains random Time generators, returning time string in certain particular format
func GetDateTimer ¶
func GetDateTimer() DateTimer
GetDateTimer returns a new DateTimer interface of DateTime
type Dowser ¶
type Dowser interface { TitleMale(v reflect.Value) (interface{}, error) TitleFeMale(v reflect.Value) (interface{}, error) FirstName(v reflect.Value) (interface{}, error) FirstNameMale(v reflect.Value) (interface{}, error) FirstNameFemale(v reflect.Value) (interface{}, error) LastName(v reflect.Value) (interface{}, error) Name(v reflect.Value) (interface{}, error) Gender(v reflect.Value) (interface{}, error) ChineseFirstName(v reflect.Value) (interface{}, error) ChineseLastName(v reflect.Value) (interface{}, error) ChineseName(v reflect.Value) (interface{}, error) }
Dowser provides interfaces to generate random logical Names with their initials
type Identifier ¶
type Identifier interface { Digit(v reflect.Value) (interface{}, error) Hyphenated(v reflect.Value) (interface{}, error) }
Identifier ...
type Internet ¶
type Internet struct{}
Internet struct
func (Internet) DomainName ¶
DomainName generates random domain name
func (Internet) MacAddress ¶
MacAddress generates random MacAddress
type Lorem ¶
type Lorem struct { }
Lorem struct
func (Lorem) Paragraph ¶
Paragraph returns a series of sentences as a paragraph using the wordList const
type Money ¶
type Money interface { Currency(v reflect.Value) (interface{}, error) Amount(v reflect.Value) (interface{}, error) AmountWithCurrency(v reflect.Value) (interface{}, error) }
Money provides an interface to generate a custom price with or without a random currency code
type Networker ¶
type Networker interface { Email(v reflect.Value) (interface{}, error) MacAddress(v reflect.Value) (interface{}, error) DomainName(v reflect.Value) (interface{}, error) URL(v reflect.Value) (interface{}, error) UserName(v reflect.Value) (interface{}, error) IPv4(v reflect.Value) (interface{}, error) IPv6(v reflect.Value) (interface{}, error) Password(v reflect.Value) (interface{}, error) Jwt(v reflect.Value) (interface{}, error) }
Networker is logical layer for Internet
func GetNetworker ¶
func GetNetworker() Networker
GetNetworker returns a new Networker interface of Internet
type Payment ¶
type Payment struct{}
Payment struct
func (Payment) CreditCardNumber ¶
CreditCardNumber generated credit card number according to the card number rules
type Person ¶
type Person struct { }
Person struct
func (Person) ChineseFirstName ¶ added in v3.8.0
ChineseFirstName returns a random chinese first name
func (Person) ChineseLastName ¶ added in v3.8.0
ChineseLastName returns a random chinese last name
func (Person) ChineseName ¶ added in v3.8.0
ChineseName returns a random nhinese name
func (Person) FirstNameFemale ¶
FirstNameFemale returns first names for females
func (Person) FirstNameMale ¶
FirstNameMale returns first names for males
func (Person) TitleFeMale ¶
TitleFeMale generates random titles for females
type Phone ¶
type Phone struct { }
Phone struct
func (Phone) E164PhoneNumber ¶
E164PhoneNumber generates phone numbers of type: "+27113456789"
func (Phone) PhoneNumber ¶
PhoneNumber generates phone numbers of type: "201-886-0269"
type Phoner ¶
type Phoner interface { PhoneNumber(v reflect.Value) (interface{}, error) TollFreePhoneNumber(v reflect.Value) (interface{}, error) E164PhoneNumber(v reflect.Value) (interface{}, error) }
Phoner serves overall tele-phonic contact generator
type Price ¶
type Price struct { }
Price struct
func (Price) Amount ¶
Amount returns a random floating price amount with a random precision of [1,2] up to (10**8 - 1)
func (Price) AmountWithCurrency ¶
AmountWithCurrency combines both price and currency together
type Render ¶
type Render interface { CreditCardType(v reflect.Value) (interface{}, error) CreditCardNumber(v reflect.Value) (interface{}, error) }
Render contains Whole Random Credit Card Generators with their types
func GetPayment ¶
func GetPayment() Render
GetPayment returns a new Render interface of Payment struct
type TaggedFunction ¶
TaggedFunction used as the standard layout function for tag providers in struct. This type also can be used for custom provider.