Documentation
¶
Overview ¶
package main generates realistic fake data for database seeders and tests — a lightweight alternative to faker.js/gofakeit with zero external dependencies.
There are two ways to use it:
Direct API calls, similar to faker.js (faker.person.firstName() -> f.Person.FirstName()):
f := faker.New() f.Person.FullName() f.Internet.Email() f.Address.City()
Tag-based struct population (especially useful for seeders — your model is already annotated with `db:"..."` tags for the ORM, and now you can add `fake:"..."` tags as well):
type User struct { Name string `db:"name" fake:"full_name"` Email string `db:"email" fake:"email"` Age int `db:"age" fake:"int:18,65"` }
var u User f.FillStruct(&u)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AddressGen ¶
type AddressGen struct {
// contains filtered or unexported fields
}
AddressGen — namespace faker.Address, аналог faker.location из faker.js.
func (*AddressGen) City ¶
func (a *AddressGen) City() string
func (*AddressGen) Country ¶
func (a *AddressGen) Country() string
func (*AddressGen) FullAddress ¶
func (a *AddressGen) FullAddress() string
FullAddress собирает улицу, город, страну и индекс в одну строку.
func (*AddressGen) Street ¶
func (a *AddressGen) Street() string
func (*AddressGen) ZipCode ¶
func (a *AddressGen) ZipCode() string
type CompanyGen ¶
type CompanyGen struct {
// contains filtered or unexported fields
}
CompanyGen — namespace faker.Company, аналог faker.company из faker.js.
func (*CompanyGen) JobTitle ¶
func (c *CompanyGen) JobTitle() string
func (*CompanyGen) Name ¶
func (c *CompanyGen) Name() string
type DateGen ¶
type DateGen struct {
// contains filtered or unexported fields
}
DateGen — namespace faker.Date, аналог faker.date из faker.js.
func (*DateGen) Birthday ¶
Birthday возвращает дату рождения для возраста в диапазоне [minAge, maxAge].
type Faker ¶
type Faker struct {
// Locale affects Person and Address generators: "en" (default) or "ru".
// Lorem always generates classic pseudo-Latin lorem ipsum text, since
// that's the industry standard placeholder and is not localized.
Locale string
Person *PersonGen
Internet *InternetGen
Address *AddressGen
Company *CompanyGen
Lorem *LoremGen
Date *DateGen
// contains filtered or unexported fields
}
Faker generates fake data.
A single Faker instance is NOT safe for concurrent use without external synchronization. Create one Faker per goroutine when seeding in parallel, or protect access with your own mutex.
func New ¶
New creates a new Faker instance.
faker.New() // non-deterministic (seeded with the current time)
faker.New(42) // deterministic: the same seed always produces the same
// sequence, which is useful for reproducible tests and seed data
func (*Faker) FillSlice ¶
FillSlice заполняет dest (указатель на срез структур) n фейковыми записями.
func (*Faker) FillStruct ¶
FillStruct заполняет dest (указатель на структуру) фейковыми данными по тегам `fake:"..."`. Поддерживает встроенные (анонимные) структуры — например core.BaseModel останется нетронутым (у него нет тега fake, поле id обычно генерирует БД, а не сидер).
Поддерживаемые генераторы (имя тега -> что генерируется):
first_name, last_name, full_name, username, phone email, url, ipv4, password[:длина] city, street, country, zip_code, address company, job_title word, words:N, sentence, sentences:N, paragraph, paragraphs:N bool, uuid int:min,max, float:min,max date_past[:лет], date_future[:лет], birthday[:minAge,maxAge]
Пример:
type User struct {
Name string `fake:"full_name"`
Email string `fake:"email"`
Age int `fake:"int:18,65"`
Bio string `fake:"paragraph"`
Born time.Time `fake:"date_past:60"`
}
var u User
f.FillStruct(&u)
func (*Faker) FloatRange ¶
FloatRange returns a random floating-point number in the range [min, max).
func (*Faker) Unique ¶
func (f *Faker) Unique() *UniqueFaker
Unique returns a UniqueFaker wrapper for this Faker.
type InternetGen ¶
type InternetGen struct {
// contains filtered or unexported fields
}
InternetGen — namespace faker.Internet, аналог faker.internet из faker.js.
func (*InternetGen) Email ¶
func (i *InternetGen) Email() string
func (*InternetGen) IPv4 ¶
func (i *InternetGen) IPv4() string
func (*InternetGen) Password ¶
func (i *InternetGen) Password(length ...int) string
Password генерирует случайный пароль. По умолчанию 12 символов, опционально можно передать желаемую длину: Password(20).
func (*InternetGen) URL ¶
func (i *InternetGen) URL() string
func (*InternetGen) UserAgent ¶
func (i *InternetGen) UserAgent() string
func (*InternetGen) Username ¶
func (i *InternetGen) Username() string
Username — алиас faker.Internet.Username() к faker.Person.Username(), как в faker.js, где internet.userName() и person.firstName() пересекаются.
type LoremGen ¶
type LoremGen struct {
// contains filtered or unexported fields
}
LoremGen — namespace faker.Lorem, аналог faker.lorem из faker.js.
func (*LoremGen) Paragraphs ¶
Paragraphs генерирует n параграфов, соединённых sep (например "\n\n").
type PersonGen ¶
type PersonGen struct {
// contains filtered or unexported fields
}
PersonGen — namespace faker.Person, аналог faker.person из faker.js.
type UniqueFaker ¶
type UniqueFaker struct {
// contains filtered or unexported fields
}
UniqueFaker wraps Faker and guarantees that generators for unique fields (email, username, phone) never produce duplicates within the same Faker instance. This is especially useful when seeding tables with UNIQUE constraints.
func (*UniqueFaker) Email ¶
func (u *UniqueFaker) Email() string
func (*UniqueFaker) Phone ¶
func (u *UniqueFaker) Phone() string
func (*UniqueFaker) Username ¶
func (u *UniqueFaker) Username() string