Documentation
¶
Index ¶
- Constants
- func ServeHTMLOnFreePort(ctx context.Context, htmlGenerator func() string) error
- type BaseHTTPWrapper
- func (b *BaseHTTPWrapper) CtxWithTransaction(r *http.Request) context.Context
- func (b *BaseHTTPWrapper) CtxWithTransactionOrGenerate(r *http.Request) (context.Context, string)
- func (b *BaseHTTPWrapper) ParseBodyParams(r *http.Request) (map[string]json.RawMessage, error)
- func (b *BaseHTTPWrapper) RunBackground(rw http.ResponseWriter, r *http.Request, event string, ...) bool
- func (b *BaseHTTPWrapper) WriteJSON(rw http.ResponseWriter, resp reply.APIResponse)
- type Config
- type Endpoint
- type MediaType
- type OpenAPIComponents
- type OpenAPIFromRegistry
- type OpenAPIGenerator
- type OpenAPIInfo
- type OpenAPIServer
- type OpenAPISpec
- type OpenAPITag
- type Operation
- type ParamMapping
- type Parameter
- type PathItem
- type QueryParam
- type Registry
- type RequestBody
- type Response
- type Schema
- type SecurityScheme
- type Server
- func (s *Server) GetRegistry() *Registry
- func (s *Server) RegisterAPIInfo(isAtomic bool, hasDistrobox bool, hasKernel bool)
- func (s *Server) RegisterEndpoints(endpoints []Endpoint)
- func (s *Server) RegisterHealthCheck()
- func (s *Server) RegisterOpenAPIFromRegistry(gen OpenAPIFromRegistry)
- func (s *Server) RegisterWebSocket()
- func (s *Server) Shutdown() error
- func (s *Server) Start(ctx context.Context) error
- type WebSocketClient
- type WebSocketHub
Constants ¶
const ( DocServerHost = "127.0.0.1" DocServerStartPort = 8080 DocServerMaxPorts = 100 )
const ( PermRead = "read" PermManage = "manage" )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type BaseHTTPWrapper ¶
BaseHTTPWrapper общая база для HTTP обёрток модулей.
func (*BaseHTTPWrapper) CtxWithTransaction ¶
func (b *BaseHTTPWrapper) CtxWithTransaction(r *http.Request) context.Context
CtxWithTransaction создает контекст с transaction из запроса
func (*BaseHTTPWrapper) CtxWithTransactionOrGenerate ¶
CtxWithTransactionOrGenerate создает контекст с transaction, генерируя его если не передан
func (*BaseHTTPWrapper) ParseBodyParams ¶
func (b *BaseHTTPWrapper) ParseBodyParams(r *http.Request) (map[string]json.RawMessage, error)
ParseBodyParams парсит параметры из тела запроса
func (*BaseHTTPWrapper) RunBackground ¶
func (b *BaseHTTPWrapper) RunBackground(rw http.ResponseWriter, r *http.Request, event string, fn func(ctx context.Context) (interface{}, error)) bool
RunBackground запускает задачу в фоне
func (*BaseHTTPWrapper) WriteJSON ¶
func (b *BaseHTTPWrapper) WriteJSON(rw http.ResponseWriter, resp reply.APIResponse)
WriteJSON отправляет JSON ответ
type Config ¶
type Config struct {
ListenAddr string
APIToken string
ReadTimeout time.Duration
WriteTimeout time.Duration
}
Config конфигурация HTTP сервера
type Endpoint ¶
type Endpoint struct {
// HTTP обработчик
Handler http.HandlerFunc
// HTTP метод (GET, POST, PUT, DELETE)
HTTPMethod string
// HTTP путь (/api/v1/packages/install)
HTTPPath string
// Тип запроса (для POST/PUT) - опционально
RequestType reflect.Type
// Тип ответа
ResponseType reflect.Type
// Требуемое разрешение (manage, read)
Permission string
// Краткое описание
Summary string
// Полное описание
Description string
// Теги для группировки
Tags []string
// Query параметры (для GET) - для OpenAPI документации
QueryParams []QueryParam
// Path параметры
PathParams []string
// Маппинг параметров - для OpenAPI документации body схемы
ParamMappings []ParamMapping
// ContentType кастомный Content-Type ответа (по умолчанию application/json)
ContentType string
}
Endpoint описывает API endpoint
type MediaType ¶
type MediaType struct {
Schema *Schema `json:"schema,omitempty"`
}
MediaType тип медиа
type OpenAPIComponents ¶
type OpenAPIComponents struct {
Schemas map[string]*Schema `json:"schemas,omitempty"`
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
}
OpenAPIComponents компоненты
type OpenAPIFromRegistry ¶
type OpenAPIFromRegistry interface {
GenerateOpenAPI() map[string]interface{}
}
OpenAPIFromRegistry интерфейс для генератора OpenAPI из registry
type OpenAPIGenerator ¶
type OpenAPIGenerator struct {
// contains filtered or unexported fields
}
OpenAPIGenerator генератор OpenAPI из registry
func NewOpenAPIGenerator ¶
func NewOpenAPIGenerator(registry *Registry, version string, listenAddr string) *OpenAPIGenerator
NewOpenAPIGenerator создает новый генератор
func (*OpenAPIGenerator) Generate ¶
func (g *OpenAPIGenerator) Generate() *OpenAPISpec
Generate генерирует OpenAPI спецификацию
func (*OpenAPIGenerator) GenerateOpenAPI ¶
func (g *OpenAPIGenerator) GenerateOpenAPI() map[string]interface{}
GenerateOpenAPI генерирует OpenAPI спецификацию как map для интерфейса http_server
type OpenAPIInfo ¶
type OpenAPIInfo struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
Version string `json:"version"`
}
OpenAPIInfo информация об API
type OpenAPIServer ¶
type OpenAPIServer struct {
URL string `json:"url"`
Description string `json:"description,omitempty"`
}
OpenAPIServer сервер API
type OpenAPISpec ¶
type OpenAPISpec struct {
OpenAPI string `json:"openapi"`
Info OpenAPIInfo `json:"info"`
Servers []OpenAPIServer `json:"servers,omitempty"`
Paths map[string]PathItem `json:"paths"`
Components OpenAPIComponents `json:"components,omitempty"`
Tags []OpenAPITag `json:"tags,omitempty"`
Security []map[string][]string `json:"security,omitempty"`
}
OpenAPISpec OpenAPI 3.0 спецификация
type OpenAPITag ¶
type OpenAPITag struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
OpenAPITag тег для группировки
type Operation ¶
type Operation struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]Response `json:"responses"`
}
Operation операция API
type ParamMapping ¶
type ParamMapping struct {
// Source откуда брать: path, query, body
Source string
// Name имя в HTTP запросе
Name string
// ArgIndex индекс аргумента в методе
ArgIndex int
// Type тип параметра
Type string
// Default значение по умолчанию
Default string
}
ParamMapping описывает маппинг HTTP параметра (для OpenAPI документации)
type Parameter ¶
type Parameter struct {
Name string `json:"name"`
In string `json:"in"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Schema *Schema `json:"schema,omitempty"`
}
Parameter параметр запроса
type PathItem ¶
type PathItem struct {
Get *Operation `json:"get,omitempty"`
Post *Operation `json:"post,omitempty"`
Put *Operation `json:"put,omitempty"`
Delete *Operation `json:"delete,omitempty"`
}
PathItem элемент пути
type QueryParam ¶
QueryParam описывает query параметр
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry хранит все зарегистрированные endpoints
func (*Registry) CollectResponseTypes ¶
CollectResponseTypes собирает уникальные типы ответов из зарегистрированных endpoints
func (*Registry) GetHTTPEndpoints ¶
GetHTTPEndpoints возвращает HTTP endpoints
func (*Registry) RegisterEndpoints ¶
RegisterEndpoints регистрирует endpoints
type RequestBody ¶
type RequestBody struct {
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Content map[string]MediaType `json:"content"`
}
RequestBody тело запроса
type Response ¶
type Response struct {
Description string `json:"description"`
Content map[string]MediaType `json:"content,omitempty"`
}
Response ответ API
type Schema ¶
type Schema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Description string `json:"description,omitempty"`
Nullable bool `json:"nullable,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Ref string `json:"$ref,omitempty"`
Required []string `json:"required,omitempty"`
}
Schema схема данных
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Description string `json:"description,omitempty"`
}
SecurityScheme схема безопасности
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server HTTP сервер APM
func (*Server) GetRegistry ¶
GetRegistry возвращает registry для OpenAPI генератора
func (*Server) RegisterAPIInfo ¶
RegisterAPIInfo регистрирует эндпоинт информации об API
func (*Server) RegisterEndpoints ¶
RegisterEndpoints регистрирует endpoints: оборачивает handler в withAuth, добавляет в mux и registry
func (*Server) RegisterHealthCheck ¶
func (s *Server) RegisterHealthCheck()
RegisterHealthCheck регистрирует эндпоинт проверки здоровья
func (*Server) RegisterOpenAPIFromRegistry ¶
func (s *Server) RegisterOpenAPIFromRegistry(gen OpenAPIFromRegistry)
RegisterOpenAPIFromRegistry регистрирует OpenAPI из registry
func (*Server) RegisterWebSocket ¶
func (s *Server) RegisterWebSocket()
RegisterWebSocket регистрирует WebSocket эндпоинт для событий
type WebSocketClient ¶
type WebSocketClient struct {
// contains filtered or unexported fields
}
WebSocketClient представляет одного подключенного клиента
type WebSocketHub ¶
type WebSocketHub struct {
// contains filtered or unexported fields
}
WebSocketHub управляет WebSocket подключениями и рассылкой событий
func GetWebSocketHub ¶
func GetWebSocketHub() *WebSocketHub
GetWebSocketHub возвращает глобальный экземпляр WebSocket hub
func NewWebSocketHub ¶
func NewWebSocketHub() *WebSocketHub
NewWebSocketHub создаёт новый WebSocket hub
func (*WebSocketHub) Broadcast ¶
func (h *WebSocketHub) Broadcast(message []byte)
Broadcast отправляет сообщение всем подключённым клиентам
func (*WebSocketHub) BroadcastEvent ¶
func (h *WebSocketHub) BroadcastEvent(event interface{})
BroadcastEvent отправляет событие всем подключённым клиентам
func (*WebSocketHub) ClientCount ¶
func (h *WebSocketHub) ClientCount() int
ClientCount возвращает количество подключённых клиентов
func (*WebSocketHub) HandleWebSocket ¶
func (h *WebSocketHub) HandleWebSocket(w http.ResponseWriter, r *http.Request)
HandleWebSocket обрабатывает WebSocket подключения
func (*WebSocketHub) Run ¶
func (h *WebSocketHub) Run()
Run запускает основной цикл обработки событий hub