Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Random fake data generator written in go

License

NotificationsYou must be signed in to change notification settings

brianvoe/gofakeit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1,457 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Gofakeit

GofakeitGo Report CardTestGoDoclicense

Random data generator written in go

Support

ko-fiBuy Me A Coffee

Merch

Merch

Features

Contributors

Thank you to all our Gofakeit contributors!

Installation

gogetgithub.com/brianvoe/gofakeit/v7

Simple Usage

import"github.com/brianvoe/gofakeit/v7"gofakeit.Name()// Markus Moengofakeit.Email()// alaynawuckert@kozey.bizgofakeit.Phone()// (570)245-7485gofakeit.BS()// front-endgofakeit.BeerName()// Duvelgofakeit.Color()// MediumOrchidgofakeit.Company()// Moen, Pagac and Wuckertgofakeit.CreditCardNumber(nil)// 4287271570245748gofakeit.HackerPhrase()// Connecting the array won't do anything, we need to generate the haptic COM driver!gofakeit.JobTitle()// Directorgofakeit.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 inthis 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// orgofakeit.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 packageSource 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 lockingfaker:=gofakeit.New(0)// NewFaker takes in a source and whether or not it should be thread safefaker:=gofakeit.NewFaker(srcrand.Source,lockbool)// PCG Pseudofaker:=gofakeit.NewFaker(rand.NewPCG(11,11),true)// ChaCha8faker:=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/randfaker:=gofakeit.NewFaker(source.NewCrypto(),true)// Dumb - simple incrementing numberfaker:=gofakeit.NewFaker(source.NewDumb(11),true)

Global Rand Set

If you would like to use the simple function calls but need to use something likecrypto/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 typeas 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 datatypeFoostruct {StrstringIntintPointer*intNamestring`fake:"{firstname}"`// Any available function all lowercaseSentencestring`fake:"{sentence}"`RandStrstring`fake:"{randomstring:[hello,world]}"`Numberstring`fake:"{number:1,10}"`// Comma separated for multiple valuesRegexstring`fake:"{regex:[abcdef]{5}}"`// Generate string from regexMapmap[string]int`fakesize:"2"`Array         []string`fakesize:"2"`ArrayRange    []string`fakesize:"2,6"`BarBarSkip*string`fake:"skip"`// Set to "skip" to not generate data forSkipAlt*string`fake:"-"`// Set to "-" to not generate data forCreated       time.Time// Can take in a fake tag as well as a format tagCreatedFormat time.Time`fake:"{year}-{month}-{day}" format:"2006-01-02"`}typeBarstruct {NamestringNumberintFloatfloat32}// Pass your struct as a pointervarfFooerr:=gofakeit.Struct(&f)fmt.Println(f.Str)// hrukpttuezptneuvunhfmt.Println(f.Int)// -7825289004089916589fmt.Println(*f.Pointer)// -343806609094473732fmt.Println(f.Name)// fredfmt.Println(f.Sentence)// Record river mind.fmt.Println(f.RandStr)// worldfmt.Println(f.Number)// 4fmt.Println(f.Regex)// cbdfcfmt.Println(f.Map)// map[PxLIo:52 lxwnqhqc:846]fmt.Println(f.Array)// cbdfcfmt.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

Fakeable types

It is possible to extend a struct by implementing theFakeable interfacein 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 fortypeFriendstringfunc (c*Friend)Fake(f*gofakeit.Faker) (any,error) {// Can call any other faker methodsreturnf.RandomString([]string{"billy","fred","susan"}),nil}// Custom time that you want to generate your own data fortypeAge time.Timefunc (c*Age)Fake(f*gofakeit.Faker) (any,error) {returnAge(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 tagstypeUserstruct {NameFriendAge*Age}varuUsergofakeit.Struct(&u)fmt.Println(u.Name)// billyfmt.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 serveror gofakeit command sub packages. You can do so via the AddFuncLookup. Each function has their own lookup, ifyou need more reference examples you can look at each files lookups.

// Simplegofakeit.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) {returnf.RandomString([]string{"bill","bob","sally"}),nil},})// With Paramsgofakeit.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")iferr!=nil {returnnil,err}split:=strings.Split(word,"")f.ShuffleStrings(split)returnstrings.Join(split,""),nil},})typeFoostruct {FriendNamestring`fake:"{friendname}"`JumbleWordstring`fake:"{jumbleword:helloworld}"`}varfFoogofakeit.Struct(&f)fmt.Println(f.FriendName)// billfmt.Println(f.JumbleWord)// loredlowlh

Templates

Generate custom outputs using golang's template enginehttps://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(sstring)string// Make string upper case-ToLower(sstring)string// Make string lower case-ToString(sany)// Convert to string-ToDate(sstring)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(mapIany)any

Example Usages

import"github.com/brianvoe/gofakeit/v7"funcmain() {// 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})iferr!=nil {fmt.Println(err)}fmt.Println(value)}

Output:

Subject: HelloDear Krajcik,Greetings!Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem. Quia voluptatem voluptatem voluptatem.Warm regardsKaitlyn Krajcikkaitlynkrajcik@krajcik570-245-7485

Functions

All functions also exist as methods on the Faker struct

File

Passingnil toCSV,JSON orXML will auto generate data using default values.

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

Template

Passingnil 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()stringUUID()string

Product

Product()*ProductInfoProductName()stringProductDescription()stringProductCategory()stringProductFeature()stringProductMaterial()stringProductUPC()stringProductAudience()stringProductDimension()stringProductUseCase()stringProductBenefit()stringProductSuffix()stringProductISBN(opts*ISBNOptions)string

Person

Person()*PersonInfoName()stringNamePrefix()stringNameSuffix()stringFirstName()stringMiddleName()stringLastName()stringGender()stringAge()intEthnicity()stringSSN()stringEIN()stringHobby()stringContact()*ContactInfoEmail()stringPhone()stringPhoneFormatted()stringTeams(peopleArray []string,teamsArray []string)map[string][]string

Generate

Struct(vany)Slice(vany)Map()map[string]anyGenerate(valuestring)stringRegex(valuestring)string

Auth

Username()stringPassword(lowerbool,upperbool,numericbool,specialbool,spacebool,numint)string

Address

Address()*AddressInfoCity()stringCountry()stringCountryAbr()stringState()stringStateAbr()stringStreet()stringStreetName()stringStreetNumber()stringStreetPrefix()stringStreetSuffix()stringUnit()stringZip()stringLatitude()float64LatitudeInRange(min,maxfloat64) (float64,error)Longitude()float64LongitudeInRange(min,maxfloat64) (float64,error)

Game

Gamertag()stringDice(numDiceuint,sides []uint) []uint

Beer

BeerAlcohol()stringBeerBlg()stringBeerHop()stringBeerIbu()stringBeerMalt()stringBeerName()stringBeerStyle()stringBeerYeast()string

Car

Car()*CarInfoCarMaker()stringCarModel()stringCarType()stringCarFuelType()stringCarTransmissionType()string

Words

// NounsNoun()stringNounCommon()stringNounConcrete()stringNounAbstract()stringNounCollectivePeople()stringNounCollectiveAnimal()stringNounCollectiveThing()stringNounCountable()stringNounUncountable()string// VerbsVerb()stringVerbAction()stringVerbLinking()stringVerbHelping()string// AdverbsAdverb()stringAdverbManner()stringAdverbDegree()stringAdverbPlace()stringAdverbTimeDefinite()stringAdverbTimeIndefinite()stringAdverbFrequencyDefinite()stringAdverbFrequencyIndefinite()string// PropositionsPreposition()stringPrepositionSimple()stringPrepositionDouble()stringPrepositionCompound()string// AdjectivesAdjective()stringAdjectiveDescriptive()stringAdjectiveQuantitative()stringAdjectiveProper()stringAdjectiveDemonstrative()stringAdjectivePossessive()stringAdjectiveInterrogative()stringAdjectiveIndefinite()string// PronounsPronoun()stringPronounPersonal()stringPronounObject()stringPronounPossessive()stringPronounReflective()stringPronounDemonstrative()stringPronounInterrogative()stringPronounRelative()string// ConnectivesConnective()stringConnectiveTime()stringConnectiveComparative()stringConnectiveComplaint()stringConnectiveListing()stringConnectiveCasual()stringConnectiveExamplify()string// WordsWord()string// TextSentence()stringParagraph()stringLoremIpsumWord()stringLoremIpsumSentence(wordCountint)stringLoremIpsumParagraph(paragraphCountint,sentenceCountint,wordCountint,separatorstring)stringQuestion()stringQuote()stringPhrase()string

Foods

Fruit()stringVegetable()stringBreakfast()stringLunch()stringDinner()stringSnack()stringDessert()string

Misc

Bool()boolWeighted(options []any,weights []float32) (any,error)FlipACoin()stringRandomMapKey(mapIany)anyShuffleAnySlice(vany)

Colors

Color()stringHexColor()stringRGBColor() []intSafeColor()stringNiceColors()string

Images

Image(widthint,heightint)*img.RGBAImageJpeg(widthint,heightint) []byteImagePng(widthint,heightint) []byte

Internet

URL()stringUrlSlug(wordsint)stringDomainName()stringDomainSuffix()stringIPv4Address()stringIPv6Address()stringMacAddress()stringHTTPStatusCode()stringHTTPStatusCodeSimple()intLogLevel(logTypestring)stringHTTPMethod()stringHTTPVersion()stringUserAgent()stringChromeUserAgent()stringFirefoxUserAgent()stringOperaUserAgent()stringSafariUserAgent()stringAPIUserAgent()string

HTML

InputName()stringSvg(options*SVGOptions)string

Date/Time

Date()time.TimePastDate()time.TimeFutureDate()time.TimeDateRange(start,endtime.Time)time.TimeNanoSecond()intSecond()intMinute()intHour()intMonth()intMonthString()stringDay()intWeekDay()stringYear()intTimeZone()stringTimeZoneAbv()stringTimeZoneFull()stringTimeZoneOffset()float32TimeZoneRegion()string

Payment

Price(min,maxfloat64)float64CreditCard()*CreditCardInfoCreditCardCvv()stringCreditCardExp()stringCreditCardNumber(*CreditCardOptions)stringCreditCardType()stringCurrency()*CurrencyInfoCurrencyLong()stringCurrencyShort()stringAchRouting()stringAchAccount()stringBitcoinAddress()stringBitcoinPrivateKey()stringBankName()stringBankType()string

Finance

Cusip()stringIsin()string

Company

BS()stringBlurb()stringBuzzWord()stringCompany()stringCompanySuffix()stringJob()*JobInfoJobDescriptor()stringJobLevel()stringJobTitle()stringSlogan()string

Hacker

HackerAbbreviation()stringHackerAdjective()stringHackeringverb()stringHackerNoun()stringHackerPhrase()stringHackerVerb()string

Hipster

HipsterWord()stringHipsterSentence()stringHipsterParagraph()string

App

AppName()stringAppVersion()stringAppAuthor()string

Animal

PetName()stringAnimal()stringAnimalType()stringFarmAnimal()stringCat()stringDog()stringBird()string

Emoji

Emoji()stringEmojiCategory()stringEmojiAlias()stringEmojiTag()stringEmojiFlag()stringEmojiAnimal()stringEmojiFood()stringEmojiPlant()stringEmojiMusic()stringEmojiVehicle()stringEmojiSport()stringEmojiFace()stringEmojiHand()stringEmojiClothing()stringEmojiLandmark()stringEmojiElectronics()stringEmojiGame()stringEmojiTools()stringEmojiWeather()stringEmojiJob()stringEmojiPerson()stringEmojiGesture()stringEmojiCostume()stringEmojiSentence()string

Language

Language()stringLanguageAbbreviation()stringProgrammingLanguage()string

Number

Number(minint,maxint)intInt()intIntN(nint)intInt8()int8Int16()int16Int32()int32Int64()int64Uint()uintUintN(nuint)uintUint8()uint8Uint16()uint16Uint32()uint32Uint64()uint64Float32()float32Float32Range(min,maxfloat32)float32Float64()float64Float64Range(min,maxfloat64)float64ShuffleInts(a []int)RandomInt(i []int)intHexUint(bitsizeint)string

String

Digit()stringDigitN(nuint)stringLetter()stringLetterN(nuint)stringLexify(strstring)stringNumerify(strstring)stringShuffleStrings(a []string)RandomString(a []string)string

Celebrity

CelebrityActor()stringCelebrityBusiness()stringCelebritySport()string

Minecraft

MinecraftOre()stringMinecraftWood()stringMinecraftArmorTier()stringMinecraftArmorPart()stringMinecraftWeapon()stringMinecraftTool()stringMinecraftDye()stringMinecraftFood()stringMinecraftAnimal()stringMinecraftVillagerJob()stringMinecraftVillagerStation()stringMinecraftVillagerLevel()stringMinecraftMobPassive()stringMinecraftMobNeutral()stringMinecraftMobHostile()stringMinecraftMobBoss()stringMinecraftBiome()stringMinecraftWeather()string

Book

Book()*BookInfoBookTitle()stringBookAuthor()stringBookGenre()string

Movie

Movie()*MovieInfoMovieName()stringMovieGenre()string

Error

Error()errorErrorDatabase()errorErrorGRPC()errorErrorHTTP()errorErrorHTTPClient()errorErrorHTTPServer()errorErrorRuntime()error

School

School()string

Song

Song()*SongInfoSongName()stringSongArtist()stringSongGenre()string

[8]ページ先頭

©2009-2026 Movatter.jp