Random fake data and struct generator for Go.

Faker

Go Go Report Card codecov awesome-go GoReference

Random fake data and struct generator for Go.

  • More than 100 generator functions
  • Struct generator
  • Unique data generator
  • Builtin types support
  • Easily customizable
  • Zero dependencies
  • Recursive infinite loop detector
  • Benchmarks (coming soon)

Installation

go get github.com/pioz/faker

Example

faker.SetSeed(623)

fmt.Println(faker.Username())
fmt.Println(faker.String())
fmt.Println(faker.IntInRange(1, 10))
fmt.Println(faker.CurrencyName())
// Output: spicule
// gzaazJyRGt3jDnVh6ik7R9FO0AU1HcOzdOXbmNVBRQ5pq8n9tHf9B21PIFozLEzsoY4wILvZjTxSLQmD3UOAamDgVR411T3YHleDTgLuz90XSO3NFZm1AnaJiJamVRcNGD2zmi4qWkcjKF3E4JKgn1DiCeC3eSb5WELsw8XqRzlvJqG
// 10
// Myanmar Kyat

Please refer to the godoc for all available functions and more.

Struct Builder Example

faker.SetSeed(622)

// Define a new builder
colorBuilder := func(params ...string) (interface{}, error) {
  return faker.Pick("Red", "Yellow", "Blue", "Black", "White"), nil
}

// Register a new builder named "color" for string type
err := faker.RegisterBuilder("color", "string", colorBuilder)
if err != nil {
  panic(err)
}

type Animal struct {
  Name  string `faker:"username"`
  Color string `faker:"color"` // Use custom color builder
}

type Person struct {
  FirstName string            `faker:"firstName"`         // Any available function case insensitive
  LastName  *string           `faker:"lastName"`          // Pointer are also supported
  Age       int               `faker:"intinrange(0,120)"` // Can call with parameters
  UUID      string            `faker:"uuid;unique"`       // Guarantees a unique value
  Number    int               `faker:"-"`                 // Skip this field
  Code      string            // No tag to use default builder for this field type
  Pet       Animal            // Recursively fill this struct
  Nicknames []string          `faker:"username;len=3"`          // Build an array of size 3 using faker.Username function
  Extra     map[string]string `faker:"stringWithSize(3);len=2"` // map are supported
}

p := Person{}
err = faker.Build(&p)
if err != nil {
  panic(err)
}
fmt.Println(p.FirstName)
fmt.Println(*p.LastName)
fmt.Println(p.Age)
fmt.Println(p.UUID)
fmt.Println(p.Number)
fmt.Println(p.Code)
fmt.Println(p.Pet.Name)
fmt.Println(p.Pet.Color)
fmt.Println(len(p.Nicknames))
fmt.Println(p.Nicknames[0])
fmt.Println(p.Nicknames[1])
fmt.Println(p.Nicknames[2])
fmt.Println(p.Extra)
// Output: Wilber
// Gutkowski
// 25
// ff8d6917-b920-46e6-b1be-dc2d48becfcb
// 0
// z
// honegger
// Red
// 3
// teagan
// polypeptide
// chinfest
// map[70w:3F6 gQS:isq]

Factory

One of the nice things about Faker is that it can also be used as a factory library. In fact when we call the faker.Build function if a value is not zero then it is not modified, leaving the original value. This allows you to create factory functions very easily:

faker.SetSeed(623)

type User struct {
    Username string `faker:"username"`
    Email    string `faker:"email"`
    Country  string `faker:"CountryAlpha2"`
}

italianUserFactory := func() *User {
    u := &User{Country: "IT"}
    faker.Build(u)
    return u
}

italianUser := italianUserFactory()
fmt.Println(italianUser)
// Output: &{spicule [email protected] IT}

Customization

A builder is a variadic function that will take an arbitrary number of strings as arguments and return an interface or an error. This function (builder) can be used to generate fake data and customize the behaviour of Faker. Here an example:

faker.SetSeed(1802)

// Define a new builder
builder := func(params ...string) (interface{}, error) {
    if len(params) > 0 && params[0] == "melee" {
        return faker.Pick("Barbarian", "Bard", "Fighter", "Monk", "Paladin", "Rogue"), nil
    }
    return faker.Pick("Cleric", "Druid", "Ranger", "Sorcerer", "Warlock", "Wizard"), nil
}

// Register a new builder named "dndClass" for string type
err := faker.RegisterBuilder("dndClass", "string", builder)
if err != nil {
    panic(err)
}

player := &struct {
    Class string `faker:"dndClass(melee)"`
    // other fields ...
}{}

// Build a struct with fake data
faker.Build(&player)

fmt.Println(player.Class)
// Output: Paladin

Contributing with new generator functions

If you want to contribute to faker with new generator functions please read this wiki!

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/pioz/faker/issues.

License

The package is available as open source under the terms of the MIT License.

Owner
Enrico
Web developer at @Uqido. Loving Ruby, C, brute force scripting, redhead. Geek inside. World of Warcraft and Hearthstone player.
Enrico
Similar Resources

RTS: request to struct. Generates Go structs from JSON server responses.

RTS: Request to Struct Generate Go structs definitions from JSON server responses. RTS defines type names using the specified lines in the route file

Dec 7, 2022

Align Golang struct tags

Formattag The tool is used to align golang struct's tags. eg.: Before // TestStruct this is a test struct type TestStruct struct { ID stri

Aug 1, 2022

The kprobe package allows construction of dynamic struct based on kprobe event format descriptions.

The kprobe package allows construction of dynamic struct based on kprobe event format descriptions.

Oct 27, 2021

An ease to use finit state machine golang implementation.Turn any struct to a fsm with graphviz visualization supported.

go-fsm An ease to use finit state machine golang implementation.Turn any struct to a fsm with graphviz visualization supported. usage import github.co

Dec 26, 2021

Exercise for solve problem data processing, performance and something wrong in passing data

Citcall Exercise Exercise for solve problem data processing, performance and something wrong in passing data Pengolahan data data processing - Readme

Nov 25, 2021

A distributed unique ID generator of using Sonyflake and encoded by Base58

Indigo About A distributed unique ID generator of using Sonyflake and encoded by Base58. ID max length is 11 characters by unsigned int64 max value. A

Nov 24, 2022

:guardsman: A teeny tiny and somewhat opinionated generator for your next golang project

A Yeoman Golang Generator We are very sorry Gophers, but other names for the generator where taken, so we choose go-lang. But we have gocreate as an a

Sep 27, 2022

XSD (XML Schema Definition) parser and Go/C/Java/Rust/TypeScript code generator

xgen Introduction xgen is a library written in pure Go providing a set of functions that allow you to parse XSD (XML schema definition) files. This li

Jan 1, 2023

Fast and secure initramfs generator

Fast and secure initramfs generator

Booster - fast and secure initramfs generator Initramfs is a specially crafted small root filesystem that mounted at the early stages of Linux OS boot

Dec 28, 2022
generate fake data in go

Faker for Go Usage package main import ( "github.com/manveru/faker" ) func main() { fake, err := faker.New("en") if err != nil { panic(err

Sep 29, 2022
Randomdata : a tiny help suite for generating random data

go-randomdata randomdata is a tiny help suite for generating random data such as first names (male or female) last names full names (male or female) c

Dec 5, 2021
Gountries provides: Countries (ISO-3166-1), Country Subdivisions(ISO-3166-2), Currencies (ISO 4217), Geo Coordinates(ISO-6709) as well as translations, country borders and other stuff exposed as struct data.

gountries Inspired by the countries gem for ruby. Countries (ISO-3166-1), Country Subdivisions(ISO-3166-2), Currencies (ISO 4217), Geo Coordinates(ISO

Dec 22, 2022
Go package and associated command line utility to generate random yet human-readable names and identifiers
Go package and associated command line utility to generate random yet human-readable names and identifiers

namegen | What's this? Go package and associated command line utility to generate random yet human-readable names and identifiers. Somewhat inspired b

Oct 19, 2022
Helps exercise your memory by giving you random tokens and poems to memorize.

memory-enhancer Helps exercise your memory by giving you random tokens and poems to memorize. Using Every day when you first open your terminal you wi

Nov 9, 2021
Generate random, pronounceable, sometimes even memorable, "superhero like" codenames - just like Docker does with container names.

Codename an RFC1178 implementation to generate pronounceable, sometimes even memorable, "superheroe like" codenames, consisting of a random combinatio

Dec 11, 2022
A repository of random code snippets used to develop proof of concepts

Oddments Oddments is a repository of random code snippets used to develop proof of concepts for techniques used with the Windows operating system. POC

Oct 13, 2022
Rfpm - Random Fair Preemption Model For Golang

rfpm RFPM (Random Fair Preemption Model) is absolutely fair to all clients who r

Jan 7, 2022
Package reservoir samples values uniformly at random from an unbounded sequence of inputs

Package reservoir samples values uniformly at random from an unbounded sequence of inputs

Oct 5, 2022
Provide Go Statistics Handler, Struct, Measure Method

Go Statistics Handler About The gosh is an abbreviation for Go Statistics Handler. This Repository is provided following functions. Go runtime statist

Jan 8, 2023