Documentation
¶
Overview ¶
Обработка прикладных HTTP запросов
Описание структур для API и инициализация ¶
Описание структур для API и инициализация
Index ¶
- Constants
- Variables
- func AddTag(tag *Tag) error
- func BadRequest(msg string, v ...any) (code int, err error)
- func CheckPeriod(from time.Time, to time.Time, maxPeriod time.Duration, stdPeriod time.Duration) (normFrom time.Time, normTo time.Time, code int, err error)
- func Conflict(msg string, v ...any) (code int, err error)
- func DelSubstArg(vars []any, name string) (result []any)
- func Enumerate(e Enumerator) (err error)
- func FindSubstArg(vars []any, name string) (subst *db.SubstArg)
- func Forbidden(msg string, v ...any) (code int, err error)
- func GetTagName(name string) string
- func Handler(h *stdhttp.HTTP, id uint64, prefix string, urlPath string, ...) (basePath string, processed bool)
- func HandlerEx(find FindModule, extra any, h *stdhttp.HTTP, id uint64, prefix string, ...) (basePath string, processed bool)
- func Init(cfg any, hh *stdhttp.HTTP, basePath string, defaultDB string, ...) (err error)
- func InternalServerError(msg string, v ...any) (code int, err error)
- func ModuleRegistration(handler API) (err error)
- func NotAllowed(msg string, v ...any) (code int, err error)
- func NotFound(msg string, v ...any) (code int, err error)
- func NotImplemented(msg string, v ...any) (code int, err error)
- func ParseTime(s string) (t time.Time, err error)
- func RemoveModuleRegistration(handler API) (err error)
- func ServiceUnavailable(msg string, v ...any) (code int, err error)
- func Start() (err error)
- func TooManyRequests(msg string, v ...any) (code int, err error)
- func Unauthorized(msg string, v ...any) (code int, err error)
- func UnprocessableEntity(msg string, v ...any) (code int, err error)
- type API
- type ByRow
- type ByRowTuner
- type Enumerator
- type ExecResult
- type ExecResultRow
- func (r *ExecResultRow) AddError(err error)
- func (r *ExecResultRow) AddErrors(errs []error)
- func (r *ExecResultRow) AddMessage(s string, params ...any)
- func (r *ExecResultRow) AddMessages(ss []string)
- func (r *ExecResultRow) Errors() (err []error)
- func (r *ExecResultRow) FillMessages()
- func (r *ExecResultRow) GetCode() (code int)
- func (r *ExecResultRow) HasErrors() bool
- func (r *ExecResultRow) SetCode(code int)
- type ExternalDocs
- type FieldDef
- type FindModule
- type FuncHandler
- type FuncInit
- type FuncResultTuner
- type Info
- type MessagesBlock
- func (m *MessagesBlock) AddError(err error)
- func (m *MessagesBlock) AddErrors(errs []error)
- func (m *MessagesBlock) AddMessage(s string, params ...any)
- func (m *MessagesBlock) AddMessages(ss []string)
- func (m *MessagesBlock) Errors() (errs []error)
- func (m *MessagesBlock) FillMessages()
- func (m *MessagesBlock) HasErrors() bool
- type Module
- type ProcOptions
- func (proc *ProcOptions) Delete() (result any, code int, err error)
- func (proc *ProcOptions) Get() (result any, code int, err error)
- func (proc *ProcOptions) GetDB() (db *db.DB, tx *sqlx.Tx)
- func (proc *ProcOptions) Others() (result any, code int, err error)
- func (proc *ProcOptions) Patch() (result any, code int, err error)
- func (proc *ProcOptions) Post() (result any, code int, err error)
- func (proc *ProcOptions) Put() (result any, code int, err error)
- func (po *ProcOptions) QueryParamFound(name string) bool
- type RowData
- type Tag
- type Tags
Constants ¶
View Source
const ( EmptyGUID = "00000000-0000-0000-0000-000000000000" FlagLogUnknownParams = 0x00000001 // Логировать полученные query параметры, которые не описаны в методе FlagConvertReplyToJSON = 0x00000008 // Конвертировать ответ в json? Если он будет заранее подготовлен уже в таком формате, то НЕ СТАВИТЬ этот флаг! // Использовать по возможности стандартные имена! ParamCount = "count" ParamPeriodFrom = "from" // включая ParamPeriodTo = "to" // НЕ включая ParamIDs = "ids" ParamNames = "names" // Стандартные Scope цепочек разбора пути, они же и суффиксы именён запросов в базу ScopeSelectAll = "select.all" ScopeSelectID = "select.id" ScopeSelectGUID = "select.guid" ScopeSelectName = "select.name" ScopeSelectPattern = "select.pattern" ScopeSelectStatus = "select.status" ScopeInsert = "insert" ScopeUpdateID = "update.id" ScopeUpdateGUID = "update.guid" ScopeUpdateName = "update.name" ScopeDeleteID = "delete.id" ScopeDeleteGUID = "delete.guid" ScopeDeleteName = "delete.name" // Признак статуса StatusActive = "active" StatusInactive = "inactive" ExprID = "id" ExprGUID = "guid" ExprName = "name" ExprPattern = "pattern" // Стандартные регулярки для Expr REempty = `` REany = `.+` REid = `\d+` REstatus = StatusActive + "|" + StatusInactive REguid = `(?i)([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})` ErrorResultName = "errorResult" ExecResultName = "execResult" ExecResultRowName = "execResultRow" DefaultMaxCount = 10000 DefaultMaxPeriod = config.Duration(3600 * time.Second) StatusProcessed = 999 // Специальный http status, говорящий о том, что все ответы уже отправлены StatusRetry = 998 // Специальный http status, возвращаемый из After для повторного выполнения GET запроса (с возможно измененными там параметрами) DBtypeNone = "-" )
Variables ¶
View Source
var ( ByRowDefautlBegin = []byte{'['} ByRowDefautlEnd = []byte{']'} ByRowDefaultSeparator = []byte{','} )
View Source
var (
Log = log.NewFacility("api") // Log facility
)
Functions ¶
func CheckPeriod ¶
func DelSubstArg ¶
func Enumerate ¶
func Enumerate(e Enumerator) (err error)
func GetTagName ¶
func Handler ¶
func Handler(h *stdhttp.HTTP, id uint64, prefix string, urlPath string, w http.ResponseWriter, r *http.Request) (basePath string, processed bool)
Обработчик прикладных HTTP запросов
func ModuleRegistration ¶
func ServiceUnavailable ¶ added in v4.0.44
func TooManyRequests ¶ added in v4.0.44
Types ¶
type API ¶
type API interface {
// Получение информации о методе
Info() *Info
// Вызывается в самом начале обработки rest, используется, например, первичной настройки или проверок
Prepare(proc *ProcOptions) (result any, code int, err error)
// Вызывается перед обращением к базе, используется, например, для добавления дополнительных параметров или проверок
Before(proc *ProcOptions) (result any, code int, err error)
// Вызывается после обращения к базе, используется, например, для обогащения результата
After(proc *ProcOptions) (result any, code int, err error)
}
Интерфейс API метода
type ByRow ¶
type ByRow struct {
Begin []byte // Пишется один раз в начале
End []byte // Пишется один раз в конце
Data []RowData
RowNum int // Количество выданных строк (увеличивается в конце обработки строки)
IsFinal bool // Финал, Tuner еще раз вызывается после завершения выборки, в первом параметре опять последнее значение
// contains filtered or unexported fields
}
func NewByRow ¶
func NewByRow(proc *ProcOptions, tuner ByRowTuner, withWriter bool) (br *ByRow, err error)
type ByRowTuner ¶
type Enumerator ¶
type ExecResult ¶
type ExecResult struct {
Method string `json:"-" comment:"Method"`
TotalRows uint64 `json:"totalRows" comment:"Number of records affected"`
SuccessRows uint64 `json:"successRows" comment:"Number of records affected (success)"`
FailedRows uint64 `json:"failedRows" comment:"Number of records affected (failed)"`
Rows []*ExecResultRow `json:"rows,omitempty" comment:"Created records" ref:"execResultRow"`
}
func NewExecResult ¶ added in v4.0.6
func NewExecResult() *ExecResult
func (*ExecResult) AddRow ¶
func (r *ExecResult) AddRow(row *ExecResultRow)
func (*ExecResult) DbResultParser ¶ added in v4.0.5
func (execResult *ExecResult) DbResultParser(dbExecResult *db.Result, returnsObj *[]*ExecResultRow) (err error)
func (*ExecResult) FillMessages ¶
func (r *ExecResult) FillMessages()
func (*ExecResult) MultiDefer ¶ added in v4.0.5
func (execResult *ExecResult) MultiDefer(pResult *any, pCode *int, pErr *error)
type ExecResultRow ¶
type ExecResultRow struct {
Code int `json:"code" comment:"Result code"`
ID uint64 `json:"id,omitempty" comment:"ID of the created record"`
GUID string `json:"guid,omitempty" comment:"GUID of the created record"`
MessagesBlock
}
func NewExecResultRow ¶ added in v4.0.6
func NewExecResultRow() *ExecResultRow
func (*ExecResultRow) AddError ¶
func (r *ExecResultRow) AddError(err error)
func (*ExecResultRow) AddErrors ¶
func (r *ExecResultRow) AddErrors(errs []error)
func (*ExecResultRow) AddMessage ¶
func (r *ExecResultRow) AddMessage(s string, params ...any)
func (*ExecResultRow) AddMessages ¶
func (r *ExecResultRow) AddMessages(ss []string)
func (*ExecResultRow) Errors ¶
func (r *ExecResultRow) Errors() (err []error)
func (*ExecResultRow) FillMessages ¶
func (r *ExecResultRow) FillMessages()
func (*ExecResultRow) GetCode ¶ added in v4.0.8
func (r *ExecResultRow) GetCode() (code int)
func (*ExecResultRow) HasErrors ¶
func (r *ExecResultRow) HasErrors() bool
func (*ExecResultRow) SetCode ¶ added in v4.0.8
func (r *ExecResultRow) SetCode(code int)
type ExternalDocs ¶
type FindModule ¶
type FuncHandler ¶ added in v4.0.43
type FuncHandler func(proc *ProcOptions) (result any, code int, err error)
type FuncResultTuner ¶
type Info ¶
type Info struct {
Path string // Относительный (от базового) путь в URL
Name string // Имя, желательно чтобы по правилам имен переменных
Summary string // Краткое описание
Description string // Описание, по умолчанию сформированное из Summary и query параметров
Tags []string // Имена тегов для группировки
Flags path.Flags // Флаги
Methods *path.Set // Цепочки обработки
Config any // Кастомные параметры в конфиг файле
DBtype string // Тип базы. Если пусто, то по умолчанию из конфига
WithTransactions bool // Разрешить транзакции
QueryPrefix string // Префикс имени запроса в базу
Init FuncInit // User defined Init
Prepare FuncHandler // User defined Prepare function
Before FuncHandler // User defined Before function
After FuncHandler // User defined After function
ResultTuner FuncResultTuner // The last step result tuner
// contains filtered or unexported fields
}
Информация о методе
func (*Info) InitShaping ¶ added in v4.0.17
type MessagesBlock ¶
type MessagesBlock struct {
Messages []string `json:"message,omitempty" comment:"Messages"`
// contains filtered or unexported fields
}
func (*MessagesBlock) AddError ¶
func (m *MessagesBlock) AddError(err error)
func (*MessagesBlock) AddErrors ¶
func (m *MessagesBlock) AddErrors(errs []error)
func (*MessagesBlock) AddMessage ¶
func (m *MessagesBlock) AddMessage(s string, params ...any)
func (*MessagesBlock) AddMessages ¶
func (m *MessagesBlock) AddMessages(ss []string)
func (*MessagesBlock) Errors ¶
func (m *MessagesBlock) Errors() (errs []error)
func (*MessagesBlock) FillMessages ¶
func (m *MessagesBlock) FillMessages()
func (*MessagesBlock) HasErrors ¶
func (m *MessagesBlock) HasErrors() bool
type Module ¶
type Module struct {
RawURL string
RelativeURL string // URL без учета базовой части
Handler API // Интерфейс метода
Info *Info // Информация о методе
LogFacility *log.Facility // Log facility
}
Обработчик
type ProcOptions ¶
type ProcOptions struct {
LogFacility *log.Facility // Предпочтительная facility для логирования
H *stdhttp.HTTP // HTTP листенер
LogSrc string // Строка с ID запроса для MessageWithSource
Info *Info // Информация о методе
ID uint64 // ID запроса
Prefix string // Префикс пути запроса (при работе через прокси)
Path string // Путь запроса
Tail []string // Остаток пути
R *http.Request // Запрос
W http.ResponseWriter // Интерфейс для ответа
AuthIdentity *auth.Identity // Результаты аутентификации
Chain *path.Chain // Обрабатываемая цепочка
ChainLocal path.Chain // Копия Chain для возможности ее модификации для работы с динамическими объектами. Рекомендуется использовать её, а не Chain.Parent
Scope string // Обрабатываемый Scope
RawBody []byte // Тело запроса. В R.Body уже nil!
PathParams any // Path параметры
QueryParams any // Query параметры
QueryParamsFound misc.BoolMap // Query параметры, присутствующие в запросе в явном виде
RequestParams any // Request параметры
DBtype string // Тип базы, если надо изменить на время запроса. Если пусто, то из info
DBqueryName string // Имя запроса к базе данных
DBqueryVars []any // Переменные для формирования запроса
ResultAsRows bool // Возвращать для GET не готовый результат, а *sqlx.Rows, чтобы производить разбор самостоятельно. Актуально для больших результатов.
DBqueryResult any // Результат выполненения запроса (указатель на слайс) при ResultAsRows==false
DBqueryRows *sqlx.Rows // Результат при ResultAsRows==true
Fields []misc.InterfaceMap // Поля (имя из sql запроса) для insert или update. Для select - список полей для выборки из базы, если нужны не все из объекта
ExcludedFields misc.StringMap // Поля ([name]db_name), которые надо исключить из запроса
InternalExecResult *ExecResult // Внутренний промежуточный результат выполнения
ExecResult *ExecResult // Результат выполнения Exec
ExtraHeaders misc.StringMap // Дополнительные возвращаемые HTTP заголовки
Extra any // Произвольные данные от вызывающего
Custom any // Произвольные пользовательские данные
// contains filtered or unexported fields
}
Опции запроса к методу
func (*ProcOptions) Delete ¶
func (proc *ProcOptions) Delete() (result any, code int, err error)
Delete -- удалить
func (*ProcOptions) Get ¶
func (proc *ProcOptions) Get() (result any, code int, err error)
Get -- получить данные
func (*ProcOptions) GetDB ¶ added in v4.0.15
func (proc *ProcOptions) GetDB() (db *db.DB, tx *sqlx.Tx)
func (*ProcOptions) Others ¶
func (proc *ProcOptions) Others() (result any, code int, err error)
Other -- другой запрос
func (*ProcOptions) Patch ¶ added in v4.0.18
func (proc *ProcOptions) Patch() (result any, code int, err error)
PATCH
func (*ProcOptions) Post ¶ added in v4.0.18
func (proc *ProcOptions) Post() (result any, code int, err error)
POST
func (*ProcOptions) Put ¶ added in v4.0.18
func (proc *ProcOptions) Put() (result any, code int, err error)
PUT
func (*ProcOptions) QueryParamFound ¶
func (po *ProcOptions) QueryParamFound(name string) bool
type RowData ¶
type RowData struct {
Prefix []byte // Дополнительный блок цикла, который может возвращаться из ByRowTuner и пишется перед основными данными
Suffix []byte // Дополнительный блок цикла, который может возвращаться из ByRowTuner и пишется после основных данных
Separator []byte // Разделитель строк
Data any // Основные данные цикла
}
Click to show internal directories.
Click to hide internal directories.