dadata

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2019 License: MIT Imports: 7 Imported by: 0

README

Client for DaData.ru

Forked from https://github.com/webdeskltd/dadata.

Build Status GitHub release Go Report Card GoDoc

DaData API v2

Implemented Clean and Suggest methods.

Installation

go get github.com/ekomobile/dadata

Usage

package main

import (
	"fmt"

	"github.com/ekomobile/dadata"
)

func main() {
	// By default client gets keys from `DADATA_API_KEY` and `DADATA_SECRET_KEY` environment variables.
	daData := dadata.NewClient()

	banks, err := daData.SuggestBanks(dadata.SuggestRequestParams{Query: "Кредитный", Count: 3})
	if nil != err {
		fmt.Println(err)
	}

	for _, bank := range banks {
		fmt.Println(bank.Data.Name.Full)
		fmt.Println(bank.Data.Bic)
	}

	// Output:
	// "МОСКОВСКИЙ КРЕДИТНЫЙ БАНК" (ПУБЛИЧНОЕ АКЦИОНЕРНОЕ ОБЩЕСТВО)
	// 044525659
	// КОММЕРЧЕСКИЙ БАНК "РЕСПУБЛИКАНСКИЙ КРЕДИТНЫЙ АЛЬЯНС" (ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ)
	// 044525860
	// ЖИЛИЩНО-КРЕДИТНЫЙ КОММЕРЧЕСКИЙ БАНК "ЖИЛКРЕДИТ" ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ
	// 044525325
}

Licence

MIT see LICENSE

Documentation

Overview

Package dadata implemented cleaning (https://dadata.ru/api/clean/) and suggesting (https://dadata.ru/api/suggest/)

Index

Examples

Constants

View Source
const (
	QcSuccess = 0 // Исходное значение распознано уверенно. Не требуется ручная проверка.
	QcFailure = 1 // Исходное значение распознано с допущениями или не распознано. Требуется ручная проверка.
)

Определите, нужна ли дополнительная проверка оператором, используя код качества (qc):

View Source
const (
	QcCompleteSuitable               = 0  // Пригоден для почтовой рассылки
	QcCompleteNoRegion               = 1  // Не пригоден, нет региона
	QcCompleteNoCity                 = 2  // Не пригоден, нет города
	QcCompleteNoStreet               = 3  // Не пригоден, нет улицы
	QcCompleteNotHome                = 4  // Не пригоден, нет дома
	QcCompleteNoApartment            = 5  // Пригоден для юридических лиц или частных владений (нет квартиры)
	QcCompleteNotSuitable            = 6  // Не пригоден
	QcCompleteCompleteForeignAddress = 7  // Иностранный адрес
	QcCompleteCompleteNoKLADR        = 10 // Пригоден, но низкая вероятность успешной доставки (дом не найден в КЛАДР)
)

Определите пригодность к рассылке, используя код полноты адреса (qc_complete):

View Source
const (
	QcHouseExactMatch        = 2  // Дом найден по точному совпадению (КЛАДР)	Высокая
	QcHouseNotExpansionMatch = 3  // Различие в расширении дома (КЛАДР)	Средняя
	QcHouseRangeMatch        = 4  // Дом найден по диапазону (КЛАДР)	Средняя
	QcHouseNotFound          = 10 // Дом не найден (КЛАДР)	Низкая
)

Определите вероятность успешной доставки письма по адресу, используя код проверки дома (qc_house):

View Source
const (
	QcGeoExactCoordinates = 0 // Точные координаты
	QcGeoNearestHouse     = 1 // Ближайший дом
	QcGeoStreet           = 2 // Улица
	QcGeoLocality         = 3 // Населенный пункт
	QcGeoCity             = 4 // Город
	QcGeoNotDetermined    = 5 // Координаты не определены
)

Определите точность координат адреса доставки с помощью кода qc_geo:

View Source
const (
	QcConflictFullMath   = 0 // Телефон соответствует адресу
	QcConflictCityMath   = 2 // Города адреса и телефона отличаются
	QcConflictRegionMath = 3 // Регионы адреса и телефона отличаются
)

Проверьте, указал ли клиент телефон, соответствующий его адресу, с помощью кода qc_conflict (удобно для проверки уровня риска):

Variables

This section is empty.

Functions

This section is empty.

Types

type Address

type Address struct {
	Source               string `json:"source"`                  // Исходный адрес одной строкой
	Result               string `json:"result"`                  // Стандартизованный адрес одной строкой
	PostalCode           string `json:"postal_code"`             // Индекс
	Country              string `json:"country"`                 // Страна
	RegionFiasID         string `json:"region_fias_id"`          // Код ФИАС региона
	RegionKladrID        string `json:"region_kladr_id"`         // Код КЛАДР региона
	RegionWithType       string `json:"region_with_type"`        // Регион с типом
	RegionType           string `json:"region_type"`             // Тип региона (сокращенный)
	RegionTypeFull       string `json:"region_type_full"`        // Тип региона
	Region               string `json:"region"`                  // Регион
	AreaFiasID           string `json:"area_fias_id"`            // Код ФИАС района в регионе
	AreaKladrID          string `json:"area_kladr_id"`           // Код КЛАДР района в регионе
	AreaWithType         string `json:"area_with_type"`          // Район в регионе с типом
	AreaType             string `json:"area_type"`               // Тип района в регионе (сокращенный)
	AreaTypeFull         string `json:"area_type_full"`          // Тип района в регионе
	Area                 string `json:"area"`                    // Район в регионе
	CityFiasID           string `json:"city_fias_id"`            // Код ФИАС города
	CityKladrID          string `json:"city_kladr_id"`           // Код КЛАДР города
	CityWithType         string `json:"city_with_type"`          // Город с типом
	CityType             string `json:"city_type"`               // Тип города (сокращенный)
	CityTypeFull         string `json:"city_type_full"`          // Тип города
	City                 string `json:"city"`                    // Город
	CityArea             string `json:"city_area"`               // Административный округ (только для Москвы)
	CityDistrictFiasID   string `json:"city_district_fias_id"`   // Код ФИАС района города (заполняется, только если район есть в ФИАС)
	CityDistrictKladrID  string `json:"city_district_kladr_id"`  // Код КЛАДР района города (не заполняется)
	CityDistrictWithType string `json:"city_district_with_type"` // Район города с типом
	CityDistrictType     string `json:"city_district_type"`      // Тип района города (сокращенный)
	CityDistrictTypeFull string `json:"city_district_type_full"` // Тип района города
	CityDistrict         string `json:"city_district"`           // Район города
	SettlementFiasID     string `json:"settlement_fias_id"`      // Код ФИАС нас. пункта
	SettlementKladrID    string `json:"settlement_kladr_id"`     // Код КЛАДР нас. пункта
	SettlementWithType   string `json:"settlement_with_type"`    // Населенный пункт с типом
	SettlementType       string `json:"settlement_type"`         // Тип населенного пункта (сокращенный)
	SettlementTypeFull   string `json:"settlement_type_full"`    // Тип населенного пункта
	Settlement           string `json:"settlement"`              // Населенный пункт
	StreetFiasID         string `json:"street_fias_id"`          // Код ФИАС улицы
	StreetKladrID        string `json:"street_kladr_id"`         // Код КЛАДР улицы
	StreetWithType       string `json:"street_with_type"`        // Улица с типом
	StreetType           string `json:"street_type"`             // Тип улицы (сокращенный)
	StreetTypeFull       string `json:"street_type_full"`        // Тип улицы
	Street               string `json:"street"`                  // Улица
	HouseFiasID          string `json:"house_fias_id"`           // Код ФИАС дома
	HouseKladrID         string `json:"house_kladr_id"`          // Код КЛАДР дома
	HouseType            string `json:"house_type"`              // Тип дома (сокращенный)
	HouseTypeFull        string `json:"house_type_full"`         // Тип дома
	House                string `json:"house"`                   // Дом
	BlockType            string `json:"block_type"`              // Тип корпуса/строения (сокращенный)
	BlockTypeFull        string `json:"block_type_full"`         // Тип корпуса/строения
	Block                string `json:"block"`                   // Корпус/строение
	FlatType             string `json:"flat_type"`               // Тип квартиры (сокращенный)
	FlatTypeFull         string `json:"flat_type_full"`          // Тип квартиры
	Flat                 string `json:"flat"`                    // Квартира
	FlatArea             string `json:"flat_area"`               // Площадь квартиры
	SquareMeterPrice     string `json:"square_meter_price"`      // Рыночная стоимость м²
	FlatPrice            string `json:"flat_price"`              // Рыночная стоимость квартиры
	PostalBox            string `json:"postal_box"`              // Абонентский ящик
	FiasID               string `json:"fias_id"`                 // Код ФИАС
	FiasLevel            string `json:"fias_level"`              // Уровень детализации, до которого адрес найден в ФИАС
	KladrID              string `json:"kladr_id"`                // Код КЛАДР
	CapitalMarker        string `json:"capital_marker"`          // Статус центра
	Okato                string `json:"okato"`                   // Код ОКАТО
	Oktmo                string `json:"oktmo"`                   // Код ОКТМО
	TaxOffice            string `json:"tax_office"`              // Код ИФНС для физических лиц
	Timezone             string `json:"timezone"`                // Часовой пояс
	GeoLat               string `json:"geo_lat"`                 // Координаты: широта
	GeoLon               string `json:"geo_lon"`                 // Координаты: долгота
	BeltwayHit           string `json:"beltway_hit"`             // Внутри кольцевой?
	BeltwayDistance      string `json:"beltway_distance"`        // Расстояние от кольцевой в км.

	// QualityCodeGeo для clean вызовов он int для suggest в адресе банков он string поэтому в поле поставил interface{} чтобы работало и там и там)\
	QualityCodeGeo      interface{} `json:"qc_geo,string"`      // Код точности координат
	QualityCodeComplete interface{} `json:"qc_complete,string"` // Код полноты
	QualityCodeHouse    interface{} `json:"qc_house,string"`    // Код проверки дома
	QualityCode         interface{} `json:"qc,string"`          // Код качества
	UnparsedParts       string      `json:"unparsed_parts"`     // Нераспознанная часть адреса. Для адреса
	Metro               []Metro     `json:"metro"`
}

Address base struct for datdata.Address

type BalanceResponse

type BalanceResponse struct {
	Balance float64 `json:"balance"`
}

BalanceResponse Response of API request

type Bank

type Bank struct {
	Opf                  OrganizationOPF `json:"opf"`
	Name                 BankName        `json:"name"`
	Bic                  string          `json:"bic"`                   // Банковский идентификационный код (БИК) ЦБ РФ
	Swift                string          `json:"swift"`                 // Банковский идентификационный код в системе SWIFT
	Okpo                 string          `json:"okpo"`                  // Код ОКПО
	CorrespondentAccount string          `json:"correspondent_account"` // Корреспондентский счет в ЦБ РФ
	RegistrationNumber   string          `json:"registration_number"`   // Регистрационный номер в ЦБ РФ
	// Go cannot use recursive types - thats why we need copy paste all fields to Rks
	Rkc struct {
		Opf                  OrganizationOPF   `json:"opf"`
		Name                 BankName          `json:"name"`
		Bic                  string            `json:"bic"`
		Swift                string            `json:"swift"`
		Okpo                 string            `json:"okpo"`
		CorrespondentAccount string            `json:"correspondent_account"`
		RegistrationNumber   string            `json:"registration_number"`
		Rkc                  interface{}       `json:"rkc"`
		Address              ResponseAddress   `json:"address"`
		Phone                string            `json:"phone"`
		State                OrganizationState `json:"state"`
	} `json:"rkc"` // Расчетно-кассовый центр. Объект такой же структуры, как сам банк.
	Address ResponseAddress   `json:"address"` // см ResponseAddress
	Phone   string            `json:"phone"`   // Не заполняется
	State   OrganizationState `json:"state"`
}

Bank base struct for dadata.Bank

type BankName

type BankName struct {
	Payment string `json:"payment"` // Платежное наименование
	Full    string `json:"full"`    // Полное наименование
	Short   string `json:"short"`   // Краткое наименование
}

BankName наименование банка

type Birthdate

type Birthdate struct {
	Source      string `json:"source"`    // Исходная дата
	Birthdate   string `json:"birthdate"` // Стандартизованная дата
	QualityCode int    `json:"qc"`        // Код качества
}

Birthdate base struct for dadata.Birthdate

type BoundValue

type BoundValue string

BoundValue type wrapper for suggest bounds full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=222888017

const (
	SuggestBoundRegion     BoundValue = "region"     // Регион
	SuggestBoundArea       BoundValue = "area"       // Район
	SuggestBoundCity       BoundValue = "city"       // Город
	SuggestBoundSettlement BoundValue = "settlement" // Населенный пункт
	SuggestBoundStreet     BoundValue = "street"     // Улица
	SuggestBoundHouse      BoundValue = "house"      // Дом
)

const for SuggestBound

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient Create new client of DaData. Api and secret keys see on profile page (https://dadata.ru/profile/). By default client uses `DADATA_API_KEY` and `DADATA_SECRET_KEY` environment variables.

func (*Client) AddressByID

func (c *Client) AddressByID(id string) (*ResponseAddress, error)

AddressByID find address by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

Example
daData := NewClient()
addr, err := daData.AddressByID("6300000100000")
if err != nil {
	fmt.Println(err)
	return
}

fmt.Printf("City: %s,\nFiasID: %s,\nKladr: %s\n", addr.Data.City, addr.Data.FiasID, addr.Data.KladrID)
Output:

func (*Client) AddressByIDWithCtx

func (c *Client) AddressByIDWithCtx(ctx context.Context, id string) (address *ResponseAddress, err error)

AddressByIDWithCtx find address by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*Client) AddressesByID

func (c *Client) AddressesByID(id string) ([]ResponseAddress, error)

AddressesByID find addresses by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*Client) AddressesByIDWithCtx

func (c *Client) AddressesByIDWithCtx(ctx context.Context, id string) (addresses []ResponseAddress, err error)

AddressesByIDWithCtx find addresses by Fias or Kladr see full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=312016944

func (*Client) CleanAddresses

func (c *Client) CleanAddresses(sourceAddresses ...string) ([]Address, error)

CleanAddresses clean all provided addresses Call https://dadata.ru/api/v2/clean/address

Example
// By default client uses `DADATA_API_KEY` and `DADATA_SECRET_KEY` environment variables.
daData := NewClient()
// Or credentials may be passed as client option.
// daData := NewClient(WithCredentialProvider("API_KEY", "SECRET_KEY"))

addresses, err := daData.CleanAddresses("ул.Правды 26", "пер.Расковой 5")

if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.StreetTypeFull)
	fmt.Println(address.Street)
	fmt.Println(address.House)
}
Output:

func (*Client) CleanAddressesWithCtx

func (c *Client) CleanAddressesWithCtx(ctx context.Context, sourceAddresses ...string) (addresses []Address, err error)

CleanAddressesWithCtx clean all provided addresses Call https://dadata.ru/api/v2/clean/address

func (*Client) CleanBirthdates

func (c *Client) CleanBirthdates(sourceBirthdates ...string) ([]Birthdate, error)

CleanBirthdates clean all provided birthdates Call https://dadata.ru/api/v2/clean/birthdate

func (*Client) CleanBirthdatesWithCtx

func (c *Client) CleanBirthdatesWithCtx(ctx context.Context, sourceBirthdates ...string) (birthdates []Birthdate, err error)

CleanBirthdatesWithCtx clean all provided birthdates Call https://dadata.ru/api/v2/clean/birthdate

func (*Client) CleanEmails

func (c *Client) CleanEmails(sourceEmails ...string) ([]Email, error)

CleanEmails clean all provided emails Call https://dadata.ru/api/v2/clean/email

func (*Client) CleanEmailsWithCtx

func (c *Client) CleanEmailsWithCtx(ctx context.Context, sourceEmails ...string) (emails []Email, err error)

CleanEmailsWithCtx clean all provided emails Call https://dadata.ru/api/v2/clean/email

func (*Client) CleanNames

func (c *Client) CleanNames(sourceNames ...string) ([]Name, error)

CleanNames clean all provided names Call https://dadata.ru/api/v2/clean/name

Example
daData := NewClient()

names, err := daData.CleanNames("Алексей Иванов", "Иван Алексеев")
if nil != err {
	fmt.Println(err)
}

for _, name := range names {
	fmt.Println(name.Surname)
	fmt.Println(name.Name)
}
Output:

func (*Client) CleanNamesWithCtx

func (c *Client) CleanNamesWithCtx(ctx context.Context, sourceNames ...string) (names []Name, err error)

CleanNamesWithCtx clean all provided names Call https://dadata.ru/api/v2/clean/name

func (*Client) CleanPassports

func (c *Client) CleanPassports(sourcePassports ...string) ([]Passport, error)

CleanPassports clean all provided passports Call https://dadata.ru/api/v2/clean/passport

func (*Client) CleanPassportsWithCtx

func (c *Client) CleanPassportsWithCtx(ctx context.Context, sourcePassports ...string) (passports []Passport, err error)

CleanPassportsWithCtx clean all provided passports Call https://dadata.ru/api/v2/clean/passport

func (*Client) CleanPhones

func (c *Client) CleanPhones(sourcePhones ...string) ([]Phone, error)

CleanPhones clean all provided phones Call https://dadata.ru/api/v2/clean/phone

func (*Client) CleanPhonesWithCtx

func (c *Client) CleanPhonesWithCtx(ctx context.Context, sourcePhones ...string) (phones []Phone, err error)

CleanPhonesWithCtx clean all provided phones Call https://dadata.ru/api/v2/clean/phone

func (*Client) CleanVehicles

func (c *Client) CleanVehicles(sourceVehicles ...string) ([]Vehicle, error)

CleanVehicles clean all provided vehicles Call https://dadata.ru/api/v2/clean/vehicle

func (*Client) CleanVehiclesWithCtx

func (c *Client) CleanVehiclesWithCtx(ctx context.Context, sourceVehicles ...string) (vehicles []Vehicle, err error)

CleanVehiclesWithCtx clean all provided vehicles Call https://dadata.ru/api/v2/clean/vehicle

func (*Client) CountriesByID

func (c *Client) CountriesByID(id string) ([]ResponseCountry, error)

CountriesByID find countries by ID

func (*Client) CountriesByIDWithCtx

func (c *Client) CountriesByIDWithCtx(ctx context.Context, id string) (addresses []ResponseCountry, err error)

CountriesByIDWithCtx find countries by ID

func (*Client) CountryByID

func (c *Client) CountryByID(id string) (*ResponseCountry, error)

CountryByID find country by ID

func (*Client) CountryByIDWithCtx

func (c *Client) CountryByIDWithCtx(ctx context.Context, id string) (country *ResponseCountry, err error)

CountryByIDWithCtx find country by ID

func (*Client) DailyStat

func (c *Client) DailyStat(date time.Time) (*StatResponse, error)

DailyStat return daily statistics see documentation https://dadata.ru/api/stat/

func (*Client) DailyStatWithCtx

func (c *Client) DailyStatWithCtx(ctx context.Context, date time.Time) (result *StatResponse, err error)

DailyStatWithCtx return daily statistics see documentation https://dadata.ru/api/stat/

func (*Client) GeoIP

func (c *Client) GeoIP(ip string) (*GeoIPResponse, error)

GeoIP try to find address by IP see documentation on:

https://dadata.ru/api/detect_address_by_ip/
https://confluence.hflabs.ru/pages/viewpage.action?pageId=715096277

ip string representation of ip-address (example 10.12.44.23) if ip=="" then dadata try to get ip-address from X-Forwarded-For header

Example
daData := NewClient()

geoIPResponse, err := daData.GeoIP("83.220.54.223")
if nil != err {
	fmt.Println(err)
	return
}
if geoIPResponse.Location == nil {
	fmt.Println("empty result from GeoIP")
	return
}
address := geoIPResponse.Location.Data
fmt.Println(address.Country)
fmt.Println(address.City)
fmt.Printf("see on https://www.google.com/maps/@%s,%sf,14z\n", address.GeoLat, address.GeoLon)
Output:

func (*Client) GeoIPWithCtx

func (c *Client) GeoIPWithCtx(ctx context.Context, ip string) (result *GeoIPResponse, err error)

GeoIPWithCtx try to find address by IP see documentation on:

https://dadata.ru/api/detect_address_by_ip/
https://confluence.hflabs.ru/pages/viewpage.action?pageId=715096277

ip string representation of ip-address (example 10.12.44.23) if ip=="" then dadata try to get ip-address from X-Forwarded-For header

func (*Client) ProfileBalance

func (c *Client) ProfileBalance() (*BalanceResponse, error)

ProfileBalance return daily statistics see documentation https://dadata.ru/api/stat/

func (*Client) ProfileBalanceWithCtx

func (c *Client) ProfileBalanceWithCtx(ctx context.Context) (result *BalanceResponse, err error)

ProfileBalanceWithCtx return daily statistics see documentation https://dadata.ru/api/stat/

func (*Client) SuggestAddresses

func (c *Client) SuggestAddresses(requestParams SuggestRequestParams) ([]ResponseAddress, error)

SuggestAddresses try to return suggest addresses by requestParams

Example
daData := NewClient()

addresses, err := daData.SuggestAddresses(SuggestRequestParams{Query: "Преснен", Count: 2})
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
	fmt.Println(address.Data.Street)
	fmt.Println(address.Data.FiasLevel)
}
Output:

Example (Granular)
daData := NewClient()

var req SuggestRequestParams

req.Query = "лен"

req.Locations = append(req.Locations, SuggestRequestParamsLocation{
	RegionFiasID: "df3d7359-afa9-4aaa-8ff9-197e73906b1c",
	CityFiasID:   "e9e684ce-7d60-4480-ba14-ca6da658188b",
})

req.FromBound = SuggestBound{SuggestBoundStreet}
req.ToBound = SuggestBound{SuggestBoundStreet}

req.RestrictValue = true
req.Count = 2

addresses, err := daData.SuggestAddresses(req)
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
	fmt.Println(address.Data.Street)
}
Output:

func (*Client) SuggestAddressesWithCtx

func (c *Client) SuggestAddressesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseAddress, err error)

SuggestAddressesWithCtx try to return suggest addresses by requestParams

Example
daData := NewClient()

var req SuggestRequestParams

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)

req.Query = "лен"

req.Locations = append(req.Locations, SuggestRequestParamsLocation{
	RegionFiasID: "df3d7359-afa9-4aaa-8ff9-197e73906b1c",
	CityFiasID:   "e9e684ce-7d60-4480-ba14-ca6da658188b",
})

req.FromBound = SuggestBound{SuggestBoundStreet}
req.ToBound = SuggestBound{SuggestBoundStreet}

req.RestrictValue = true
req.Count = 2

addresses, err := daData.SuggestAddressesWithCtx(ctx, req)
if nil != err {
	fmt.Println(err)
}

for _, address := range addresses {
	fmt.Println(address.UnrestrictedValue)
}

cancel()
// if ctx is exited (by cancel or timeout) we must catch err
_, err = daData.SuggestAddressesWithCtx(ctx, req)
fmt.Println(err)
Output:

func (*Client) SuggestBanks

func (c *Client) SuggestBanks(requestParams SuggestRequestParams) ([]ResponseBank, error)

SuggestBanks try to return suggest banks by requestParams

Example
daData := NewClient()

banks, err := daData.SuggestBanks(SuggestRequestParams{Query: "Кредитный", Count: 3})
if nil != err {
	fmt.Println(err)
}

for _, bank := range banks {
	fmt.Println(bank.Data.Name.Full)
	fmt.Println(bank.Data.Bic)
}
Output:

func (*Client) SuggestBanksWithCtx

func (c *Client) SuggestBanksWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseBank, err error)

SuggestBanksWithCtx try to return suggest banks by requestParams

func (*Client) SuggestCountries

func (c *Client) SuggestCountries(requestParams SuggestRequestParams) ([]ResponseCountry, error)

SuggestCountries try to return suggest countries by requestParams

func (*Client) SuggestCountriesWithCtx

func (c *Client) SuggestCountriesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseCountry, err error)

SuggestCountriesWithCtx try to return suggest countries by requestParams

func (*Client) SuggestEmails

func (c *Client) SuggestEmails(requestParams SuggestRequestParams) ([]ResponseEmail, error)

SuggestEmails try to return suggest emails by requestParams

func (*Client) SuggestEmailsWithCtx

func (c *Client) SuggestEmailsWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseEmail, err error)

SuggestEmailsWithCtx try to return suggest emails by requestParams

func (*Client) SuggestNames

func (c *Client) SuggestNames(requestParams SuggestRequestParams) ([]ResponseName, error)

SuggestNames try to return suggest names by requestParams

func (*Client) SuggestNamesWithCtx

func (c *Client) SuggestNamesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseName, err error)

SuggestNamesWithCtx try to return suggest names by requestParams

func (*Client) SuggestParties

func (c *Client) SuggestParties(requestParams SuggestRequestParams) ([]ResponseParty, error)

SuggestParties try to return suggest parties by requestParams

Example
daData := NewClient()

parties, err := daData.SuggestParties(SuggestRequestParams{Query: "Агрохолд", Count: 3})
if nil != err {
	fmt.Println(err)
}

for _, party := range parties {
	fmt.Println(party.Data.Name.Full)
	fmt.Println(party.Data.Ogrn)
}
Output:

func (*Client) SuggestPartiesWithCtx

func (c *Client) SuggestPartiesWithCtx(ctx context.Context, requestParams SuggestRequestParams) (ret []ResponseParty, err error)

SuggestPartiesWithCtx try to return suggest parties by requestParams

type ClientOption

type ClientOption func(opts *clientOptions)

func WithBaseSuggestURL

func WithBaseSuggestURL(url string) ClientOption

func WithBaseURL

func WithBaseURL(url string) ClientOption

func WithCredentialProvider

func WithCredentialProvider(c CredentialProvider) ClientOption

WithCredentialProvider sets credential provider.

func WithHttpClient

func WithHttpClient(c *http.Client) ClientOption

type Country

type Country struct {
	Code      string `json:"code"`
	Alfa2     string `json:"alfa2"`
	Alfa3     string `json:"alfa3"`
	NameShort string `json:"name_short"`
	Name      string `json:"name"`
}

Country base struct for dadata.Country

type CredentialProvider

type CredentialProvider interface {
	ApiKey() string
	SecretKey() string
}

type Credentials

type Credentials struct {
	ApiKeyValue    string
	SecretKeyValue string
}

func (*Credentials) ApiKey

func (c *Credentials) ApiKey() string

func (*Credentials) SecretKey

func (c *Credentials) SecretKey() string

type Email

type Email struct {
	Source      string `json:"source"` // Исходный e-mail
	Email       string `json:"email"`  // Стандартизованный e-mail
	QualityCode int    `json:"qc"`     // Код качества
}

Email base struct for dadata.Email

type EnvironmentCredentials

type EnvironmentCredentials struct {
	ApiKeyName    string
	SecretKeyName string
}

func (*EnvironmentCredentials) ApiKey

func (c *EnvironmentCredentials) ApiKey() string

func (*EnvironmentCredentials) SecretKey

func (c *EnvironmentCredentials) SecretKey() string

type GeoIPResponse

type GeoIPResponse struct {
	Location *ResponseAddress `json:"location"`
}

GeoIPResponse response for GeoIP

type Metro

type Metro struct {
	Name     string  `json:"name"`
	Line     string  `json:"line"`
	Distance float64 `json:"distance"`
}

Metro base struct for dadata.Metro

type Name

type Name struct {
	Source         string      `json:"source"`          // Исходное ФИО одной строкой
	Result         string      `json:"result"`          // Стандартизованное ФИО одной строкой
	ResultGenitive string      `json:"result_genitive"` // ФИО в родительном падеже (кого?)
	ResultDative   string      `json:"result_dative"`   // ФИО в дательном падеже (кому?)
	ResultAblative string      `json:"result_ablative"` // ФИО в творительном падеже (кем?)
	Surname        string      `json:"surname"`         // Фамилия
	Name           string      `json:"name"`            // Имя
	Patronymic     string      `json:"patronymic"`      // Отчество
	Gender         string      `json:"gender"`          // Пол
	QualityCode    interface{} `json:"qc"`              // Код качества
}

Name base struct for dadata.Name

type OrganizationOPF

type OrganizationOPF struct {
	Type  string `json:"type"`  // Тип кредитной организации
	Full  string `json:"full"`  // Тип кредитной организации (на русском)
	Short string `json:"short"` // Тип кредитной организации (на русском, сокращенный)
}

OrganizationOPF Тип Кредитной организации

type OrganizationState

type OrganizationState struct {
	Status string `json:"status"` // Статус организации:
	//  ACTIVE      — действующая
	//  LIQUIDATING — ликвидируется
	//  LIQUIDATED  — ликвидирована
	ActualityDate    int64 `json:"actuality_date"`    // Дата актуальности сведений
	RegistrationDate int64 `json:"registration_date"` // Дата регистрации
	LiquidationDate  int64 `json:"liquidation_date"`  // Дата ликвидации
}

OrganizationState Статус организации

type Party

type Party struct {
	Kpp        string `json:"kpp"`
	Capital    string `json:"capital"`
	Management struct {
		Name string `json:"name"`
		Post string `json:"post"`
	} `json:"management"`
	Founders    string            `json:"founders"`
	Managers    string            `json:"managers"`
	BranchType  string            `json:"branch_type"`
	BranchCount int               `json:"branch_count"`
	Source      string            `json:"source"`
	Qc          string            `json:"qc"`
	Hid         string            `json:"hid"`
	Type        string            `json:"type"`
	State       OrganizationState `json:"state"`
	Opf         OrganizationOPF   `json:"opf"`
	Name        struct {
		FullWithOpf  string `json:"full_with_opf"`
		ShortWithOpf string `json:"short_with_opf"`
		Latin        string `json:"latin"`
		Full         string `json:"full"`
		Short        string `json:"short"`
	} `json:"name"`
	Inn         string          `json:"inn"`
	Ogrn        string          `json:"ogrn"`
	Okpo        string          `json:"okpo"`
	Okved       string          `json:"okved"`
	Okveds      string          `json:"okveds"`
	Authorities string          `json:"authorities"`
	Documents   string          `json:"documents"`
	Licenses    string          `json:"licenses"`
	Address     ResponseAddress `json:"address"`
	Phones      string          `json:"phones"`
	Emails      string          `json:"emails"`
	OgrnDate    int64           `json:"ogrn_date"`
	OkvedType   string          `json:"okved_type"`
}

Party base struct for dadata.Party (rus Организация)

type Passport

type Passport struct {
	Source      string `json:"source"` // Исходная серия и номер одной строкой
	Series      string `json:"series"` // Серия
	Number      string `json:"number"` // Номер
	QualityCode int    `json:"qc"`     // Код проверки
}

Passport base struct for dadata.Passport

type Phone

type Phone struct {
	Source              string `json:"source"`       // Исходный телефон одной строкой
	Type                string `json:"type"`         // Тип телефона
	Phone               string `json:"phone"`        // Стандартизованный телефон одной строкой
	CountryCode         string `json:"country_code"` // Код страны
	CityCode            string `json:"city_code"`    // Код города / DEF-код
	Number              string `json:"number"`       // Локальный номер телефона
	Extension           string `json:"extension"`    // Добавочный номер
	Provider            string `json:"provider"`     // Оператор связи
	Region              string `json:"region"`       // Регион
	Timezone            string `json:"timezone"`     // Часовой пояс
	QualityCodeConflict int    `json:"qc_conflict"`  // Признак конфликта телефона с адресом
	QualityCode         int    `json:"qc"`           // Код качества
}

Phone base struct for dadata.Phone

type ResponseAddress

type ResponseAddress struct {
	Value             string  `json:"value"`
	UnrestrictedValue string  `json:"unrestricted_value"`
	Data              Address `json:"data"`
}

ResponseAddress api response for address

type ResponseBank

type ResponseBank struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Bank   `json:"data"`
}

ResponseBank api response for bank

type ResponseCountry

type ResponseCountry struct {
	Value string  `json:"value"`
	Data  Country `json:"data"`
}

ResponseCountry api response for country

type ResponseEmail

type ResponseEmail struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Email  `json:"data"`
}

ResponseEmail api response for email

type ResponseName

type ResponseName struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Name   `json:"data"`
}

ResponseName api response for name

type ResponseParty

type ResponseParty struct {
	Value             string `json:"value"`
	UnrestrictedValue string `json:"unrestricted_value"`
	Data              Party  `json:"data"`
}

ResponseParty api response for party

type StatResponse

type StatResponse struct {
	Date     string `json:"date"`
	Services struct {
		Merging     int `json:"merging"`
		Suggestions int `json:"suggestions"`
		Clean       int `json:"clean"`
	} `json:"services"`
}

StatResponse usage statitics see docs https://dadata.ru/api/stat/

type SuggestAddressResponse

type SuggestAddressResponse struct {
	Suggestions []ResponseAddress `json:"suggestions"`
}

SuggestAddressResponse result slice for address suggestions

type SuggestBankResponse

type SuggestBankResponse struct {
	Suggestions []ResponseBank `json:"suggestions"`
}

SuggestBankResponse result slice for bank suggestions

type SuggestBound

type SuggestBound struct {
	Value BoundValue `json:"value"`
}

SuggestBound for granular sugestion full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=222888017

type SuggestCountryResponse

type SuggestCountryResponse struct {
	Suggestions []ResponseCountry `json:"suggestions"`
}

SuggestCountryResponse result slice for country suggestions

type SuggestEmailResponse

type SuggestEmailResponse struct {
	Suggestions []ResponseEmail `json:"suggestions"`
}

SuggestEmailResponse result slice for email suggestions

type SuggestNameResponse

type SuggestNameResponse struct {
	Suggestions []ResponseName `json:"suggestions"`
}

SuggestNameResponse result slice for name suggestions

type SuggestPartyResponse

type SuggestPartyResponse struct {
	Suggestions []ResponseParty `json:"suggestions"`
}

SuggestPartyResponse result slice for party suggestions

type SuggestRequestParams

type SuggestRequestParams struct {
	Query         string                         `json:"query"` // user input for suggestion
	Count         int                            `json:"count"` // ligmit for results
	Locations     []SuggestRequestParamsLocation `json:"locations"`
	RestrictValue bool                           `json:"restrict_value"` // don't show restricts (region) on results

	FromBound SuggestBound `json:"from_bound"`
	ToBound   SuggestBound `json:"to_bound"`
}

SuggestRequestParams Request struct

type SuggestRequestParamsLocation

type SuggestRequestParamsLocation struct {
	FiasID               string `json:"fias_id,omitempty"`
	KladrID              string `json:"kladr_id,omitempty"`
	Region               string `json:"region,omitempty"`
	RegionFiasID         string `json:"region_fias_id,omitempty"`
	RegionKladrID        string `json:"region_kladr_id,omitempty"`
	RegionTypeFull       string `json:"region_type_full,omitempty"`
	City                 string `json:"city,omitempty"`
	CityFiasID           string `json:"city_fias_id,omitempty"` // search only in this area
	CityKladrID          string `json:"city_kladr_id,omitempty"`
	CityTypeFull         string `json:"city_type_full,omitempty"`
	CityDistrictTypeFull string `json:"city_district_type_full,omitempty"`
	Settlement           string `json:"settlement,omitempty"`
	SettlementFiasID     string `json:"settlement_fias_id,omitempty"`
	SettlementKladrID    string `json:"settlement_kladr_id,omitempty"`
	SettlementTypeFull   string `json:"settlement_type_full,omitempty"`
	Street               string `json:"street,omitempty"`
	StreetFiasID         string `json:"street_fias_id,omitempty"`
	StreetKladrID        string `json:"street_kladr_id,omitempty"`
	StreetTypeFull       string `json:"street_type_full,omitempty"`
	AreaTypeFull         string `json:"area_type_full,omitempty"`
}

SuggestRequestParamsLocation constraints for suggestion full documentation https://confluence.hflabs.ru/pages/viewpage.action?pageId=204669108

type Vehicle

type Vehicle struct {
	Source      string `json:"source"` // Исходное значение
	Result      string `json:"result"` // Стандартизованное значение
	Brand       string `json:"brand"`  // Марка
	Model       string `json:"model"`  // Модель
	QualityCode int    `json:"qc"`     // Код проверки
}

Vehicle base struct for dadata.Vehicle

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL