http_server

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: GPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DocServerHost      = "127.0.0.1"
	DocServerStartPort = 8080
	DocServerMaxPorts  = 100
)
View Source
const (
	PermRead   = "read"
	PermManage = "manage"
)

Variables

This section is empty.

Functions

func ServeHTMLOnFreePort

func ServeHTMLOnFreePort(ctx context.Context, htmlGenerator func() string) error

Types

type BaseHTTPWrapper

type BaseHTTPWrapper struct {
	Ctx       context.Context
	AppConfig *app.Config
	Reporter  *reply.Reporter
}

BaseHTTPWrapper общая база для HTTP обёрток модулей.

func (*BaseHTTPWrapper) CtxWithTransaction

func (b *BaseHTTPWrapper) CtxWithTransaction(r *http.Request) context.Context

CtxWithTransaction создает контекст с transaction из запроса

func (*BaseHTTPWrapper) CtxWithTransactionOrGenerate

func (b *BaseHTTPWrapper) CtxWithTransactionOrGenerate(r *http.Request) (context.Context, string)

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 сервера

func DefaultConfig

func DefaultConfig() Config

DefaultConfig возвращает конфигурацию по умолчанию

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

type QueryParam struct {
	Name        string
	Type        string
	Required    bool
	Description string
}

QueryParam описывает query параметр

type Registry

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

Registry хранит все зарегистрированные endpoints

func NewRegistry

func NewRegistry() *Registry

NewRegistry создает новый registry

func (*Registry) CollectResponseTypes

func (r *Registry) CollectResponseTypes() map[string]reflect.Type

CollectResponseTypes собирает уникальные типы ответов из зарегистрированных endpoints

func (*Registry) GetHTTPEndpoints

func (r *Registry) GetHTTPEndpoints() []Endpoint

GetHTTPEndpoints возвращает HTTP endpoints

func (*Registry) RegisterEndpoints

func (r *Registry) RegisterEndpoints(endpoints []Endpoint)

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 NewServer

func NewServer(config Config, appConfig *app.Config) (*Server, error)

NewServer создаёт новый HTTP сервер

func (*Server) GetRegistry

func (s *Server) GetRegistry() *Registry

GetRegistry возвращает registry для OpenAPI генератора

func (*Server) RegisterAPIInfo

func (s *Server) RegisterAPIInfo(isAtomic bool, hasDistrobox bool, hasKernel bool)

RegisterAPIInfo регистрирует эндпоинт информации об API

func (*Server) RegisterEndpoints

func (s *Server) RegisterEndpoints(endpoints []Endpoint)

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 эндпоинт для событий

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown останавливает HTTP сервер

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start запускает HTTP сервер

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

Jump to

Keyboard shortcuts

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