Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2af9c4978 | ||
|
|
24a8ea2578 | ||
|
|
ebc99c6ae4 | ||
|
|
7bac2e403f | ||
|
|
1ea3ef186c | ||
|
|
1d1c5dbde6 | ||
|
|
11ef48bbeb | ||
|
|
5263e1504d | ||
|
|
06acaba5b3 | ||
|
|
2f29af5e76 | ||
|
|
3e707244dd | ||
|
|
fa8bc6c1b7 | ||
|
|
71498785ea | ||
|
|
aa68f6028a |
No files matched your search
@@ -81,3 +81,4 @@ formatters:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* Добавлено поле `application_group` в таблицу `roles`
|
||||
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
|
||||
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
|
||||
* Добавлена возможность скачивания и формирования CSV
|
||||
### v7.1.0
|
||||
* переименование авторизации через SUDIR в OAuth:
|
||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
server *http.Server
|
||||
oauthCli *httpcli.Client
|
||||
logger *log.Adapter
|
||||
bgjobCli *bgjobx.Client
|
||||
@@ -43,7 +43,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
db: db,
|
||||
server: grpc.NewServer(),
|
||||
server: http.NewServer(logger),
|
||||
logger: logger,
|
||||
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||
bgjobCli: bgjobCli,
|
||||
@@ -109,7 +109,7 @@ func (a *Assembly) Runners() []app.Runner {
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
err := a.server.ListenAndServe(a.boot.BindingAddress)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "listen ans serve grpc server")
|
||||
return errors.WithMessage(err, "listen and serve http server")
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
@@ -127,7 +127,7 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
a.boot.ClusterCli,
|
||||
app.CloserFunc(func() error {
|
||||
a.server.Shutdown()
|
||||
_ = a.server.Shutdown(context.Background())
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
|
||||
+17
-4
@@ -18,9 +18,10 @@ import (
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
@@ -44,7 +45,7 @@ func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Handler isp.BackendServiceServer
|
||||
Handler *router.Router
|
||||
BgJobCfg []bgjobx.WorkerConfig
|
||||
}
|
||||
|
||||
@@ -97,6 +98,14 @@ func (l Locator) Config(
|
||||
|
||||
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
||||
|
||||
downloadService := service.NewDownload(
|
||||
auditService,
|
||||
userService,
|
||||
tokenService,
|
||||
roleService,
|
||||
permissionsService,
|
||||
)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
authController := controller.NewAuth(authService, l.logger)
|
||||
@@ -106,8 +115,11 @@ func (l Locator) Config(
|
||||
roleController := controller.NewRole(roleService)
|
||||
permissionController := controller.NewPermissions(permissionsService)
|
||||
uiSettingsController := controller.NewUiSettings(uiSettingsService)
|
||||
downloadController := controller.NewDownload(downloadService)
|
||||
|
||||
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
|
||||
handler := routes.Handler(
|
||||
endpoint.DefaultWrapper(l.logger),
|
||||
wrapper,
|
||||
routes.Controllers{
|
||||
User: userController,
|
||||
Customization: customizationController,
|
||||
@@ -118,6 +130,7 @@ func (l Locator) Config(
|
||||
Role: roleController,
|
||||
Permissions: permissionController,
|
||||
UiSettings: uiSettingsController,
|
||||
Download: downloadController,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
// StringFromHeader extracts a string value from header by key.
|
||||
// Returns an error if header is nil or the key is not found.
|
||||
func StringFromHeader(key string, h http.Header) (string, error) {
|
||||
if h == nil {
|
||||
return "", errors.New("header is nil")
|
||||
}
|
||||
values := h.Values(key)
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in header", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromHeader extracts an integer value from header by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromHeader(key string, h http.Header) (int, error) {
|
||||
value, err := StringFromHeader(key, h)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
+36
-35
@@ -2,12 +2,12 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type AuditService interface {
|
||||
@@ -27,16 +27,17 @@ func NewAudit(service AuditService) Audit {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/all [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/all [POST]
|
||||
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -49,38 +50,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
|
||||
}
|
||||
|
||||
// Events
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditResponse true "Тело запроса"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/events [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка событий аудита
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/events [POST]
|
||||
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
||||
return c.service.Events(ctx)
|
||||
}
|
||||
|
||||
// SetEvents
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Всегда возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SetAuditEvent true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/set_events [POST]
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Установить события аудита
|
||||
// @Description Устанавливает (обновляет) набор активных событий аудита.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
|
||||
// @Success 200 {object} map[string]interface{} "События успешно установлены"
|
||||
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/set_events [POST]
|
||||
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
||||
err := c.service.SetEvents(ctx, req)
|
||||
switch {
|
||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
+64
-60
@@ -2,16 +2,15 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"isp-admin-service/auth"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type authService interface {
|
||||
@@ -33,18 +32,19 @@ func NewAuth(authService authService, logger log.Logger) Auth {
|
||||
}
|
||||
|
||||
// Logout
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,19 +58,20 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
}
|
||||
|
||||
// LogoutWithReason
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -84,28 +85,30 @@ func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logo
|
||||
}
|
||||
|
||||
// Login
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
|
||||
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login [POST]
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
||||
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login")
|
||||
default:
|
||||
@@ -114,25 +117,26 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
||||
}
|
||||
|
||||
// LoginWithOauth
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithOauth(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with oauth")
|
||||
default:
|
||||
@@ -140,15 +144,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
||||
}
|
||||
}
|
||||
|
||||
func getAdminId(authData grpc.AuthData) (int64, error) {
|
||||
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
||||
func getAdminId(r *http.Request) (int64, error) {
|
||||
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, err.Error())
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
adminId, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
return int64(adminId), nil
|
||||
|
||||
+11
-10
@@ -19,16 +19,17 @@ func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||
}
|
||||
|
||||
// GetUIDesign
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UIDesign
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_design [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UIDesign
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_design [POST]
|
||||
func (c Customization) GetUIDesign() (domain.UIDesign, error) {
|
||||
return c.uiCfg, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type DownloadService interface {
|
||||
DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error
|
||||
DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error
|
||||
DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error
|
||||
DownloadRoles(ctx context.Context, w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
type Download struct {
|
||||
service DownloadService
|
||||
}
|
||||
|
||||
func NewDownload(service DownloadService) Download {
|
||||
return Download{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Users
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список пользователей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /user/download [POST]
|
||||
func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadUsers(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download users")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sessions
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список сессий в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /session/download [POST]
|
||||
func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadSessions(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download sessions")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Audit
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать журнал аудита в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /log/download [POST]
|
||||
func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadAudit(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download audit")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Roles
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать матрицу ролей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /role/download [POST]
|
||||
func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadRoles(ctx, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download roles")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -21,13 +21,15 @@ func NewPermissions(permissionsService permissionsService) Permissions {
|
||||
}
|
||||
|
||||
// GetPermissions
|
||||
// @Tags user
|
||||
// @Summary Получить все разрашения
|
||||
// @Description Получить все разрашения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Router /user/get_permissions [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить все разрешения
|
||||
// @Description Получить все разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_permissions [POST]
|
||||
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
||||
return u.permissionsService.All(ctx)
|
||||
}
|
||||
+60
-58
@@ -2,13 +2,12 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
@@ -29,17 +28,17 @@ func NewRole(roleService roleService) Role {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RoleAllRequest true "Тело запроса"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/all [POST]
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx, req)
|
||||
if err != nil {
|
||||
@@ -50,20 +49,21 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role
|
||||
}
|
||||
|
||||
// CreateRole
|
||||
// @Tags user
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
role, err := u.roleService.Create(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create role")
|
||||
default:
|
||||
@@ -80,20 +80,21 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// UpdateRole
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -101,9 +102,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
result, err := u.roleService.Update(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "role not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update role")
|
||||
default:
|
||||
@@ -112,19 +113,20 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// DeleteRole
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+21
-19
@@ -6,7 +6,7 @@ import (
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
@@ -25,15 +25,16 @@ func NewSecure(service SecureService) Secure {
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authenticate [POST]
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authenticate [POST]
|
||||
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
||||
adminId, err := s.service.Authenticate(ctx, req.Token)
|
||||
switch {
|
||||
@@ -61,15 +62,16 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
|
||||
}
|
||||
|
||||
// Authorize
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authorize [POST]
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authorize [POST]
|
||||
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
||||
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
||||
if err != nil {
|
||||
|
||||
+22
-20
@@ -22,16 +22,17 @@ func NewSession(service SessionService) Session {
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/all [POST]
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/all [POST]
|
||||
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -44,16 +45,17 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
|
||||
}
|
||||
|
||||
// Revoke
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/revoke [POST]
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/revoke [POST]
|
||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||
return c.service.Revoke(ctx, req.Id)
|
||||
}
|
||||
+15
-14
@@ -3,10 +3,10 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type UiSettingsService interface {
|
||||
@@ -24,22 +24,23 @@ func NewUiSettings(service UiSettingsService) UiSettings {
|
||||
}
|
||||
|
||||
// UiOauthSettings
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
//
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
resp, err := c.service.OauthSettings(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnknownClient):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
|
||||
+127
-120
@@ -2,15 +2,13 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
@@ -36,19 +34,20 @@ func NewUser(userService userService) User {
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 401 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователя не существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,9 +55,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get profile")
|
||||
default:
|
||||
@@ -67,17 +66,18 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
||||
}
|
||||
|
||||
// GetUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_users [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_users [POST]
|
||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -95,16 +95,17 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
|
||||
}
|
||||
|
||||
// GetAllUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_all_users [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_all_users [POST]
|
||||
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
users, err := u.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
@@ -115,20 +116,21 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
}
|
||||
|
||||
// CreateUser
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -136,7 +138,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
default:
|
||||
@@ -145,21 +147,22 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// UpdateUser
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -167,11 +170,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
default:
|
||||
@@ -180,19 +183,20 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
||||
}
|
||||
|
||||
// DeleteUser
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -206,18 +210,19 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities
|
||||
}
|
||||
|
||||
// Block
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -230,32 +235,34 @@ func (u User) Block(ctx context.Context, authData grpc.AuthData, identities doma
|
||||
}
|
||||
|
||||
// GetById
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_by_id [POST]
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_by_id [POST]
|
||||
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
||||
return u.userService.GetById(ctx, identities.UserId)
|
||||
}
|
||||
|
||||
// ChangePassword
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -263,7 +270,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do
|
||||
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalidPassword):
|
||||
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
|
||||
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
|
||||
case err != nil:
|
||||
return apierrors.NewInternalServiceError(err)
|
||||
default:
|
||||
|
||||
+246
-134
@@ -46,19 +46,25 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Данные для авторизации не верны",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Слишком много запросов на авторизацию",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +72,7 @@
|
||||
},
|
||||
"/auth/login_with_oauth": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"description": "Авторизация с получением токена администратора.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -95,22 +101,22 @@
|
||||
"$ref": "#/definitions/domain.LoginResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Авторизация OAuth не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Некорректный код для авторизации или неизвестное название клиента",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация OAuth не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,18 +146,22 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
"description": "Успешный выход",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,6 +181,13 @@
|
||||
],
|
||||
"summary": "Выход по бездействию из авторизованной сессии",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
@@ -179,29 +196,26 @@
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LogoutRequest"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
"description": "Успешный выход",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,7 +242,7 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"description": "Тело запроса (пагинация, сортировка, фильтры)",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -247,13 +261,49 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/log/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать журнал аудита в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.AuditPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -271,7 +321,7 @@
|
||||
"tags": [
|
||||
"log"
|
||||
],
|
||||
"summary": "Получение списка логов",
|
||||
"summary": "Получение списка событий аудита",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
@@ -279,15 +329,6 @@
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.AuditResponse"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -300,16 +341,10 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,7 +352,7 @@
|
||||
},
|
||||
"/log/set_events": {
|
||||
"post": {
|
||||
"description": "Всегда возвращает полный список доступных событий аудита",
|
||||
"description": "Устанавливает (обновляет) набор активных событий аудита.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -327,7 +362,7 @@
|
||||
"tags": [
|
||||
"log"
|
||||
],
|
||||
"summary": "Получение списка логов",
|
||||
"summary": "Установить события аудита",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
@@ -337,29 +372,36 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"description": "Список событий аудита для установки",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.SetAuditEvent"
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/domain.SetAuditEvent"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
"description": "События успешно установлены",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"description": "Неизвестное событие аудита",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,15 +427,6 @@
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.RoleAllRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -409,13 +442,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -431,7 +464,7 @@
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
"role"
|
||||
],
|
||||
"summary": "Создать роль",
|
||||
"parameters": [
|
||||
@@ -456,25 +489,25 @@
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.User"
|
||||
"$ref": "#/definitions/domain.Role"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Роль с указанным именем уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -518,13 +551,38 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/role/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать матрицу ролей в csv",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -571,19 +629,19 @@
|
||||
"404": {
|
||||
"description": "Роль с указанным id не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Роль с указанным именем уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -623,7 +681,7 @@
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -663,7 +721,7 @@
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -709,13 +767,49 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/session/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать список сессий в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.SessionPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -758,13 +852,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -804,19 +898,19 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Неизвестное название клиента",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -859,13 +953,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -906,13 +1000,13 @@
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"description": "Невалидное тело запроса или неверный старый пароль",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "внутренняя ошибка",
|
||||
"description": "Внутренняя ошибка",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
@@ -961,19 +1055,19 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1020,13 +1114,49 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать список пользователей в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UsersPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1064,13 +1194,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1109,13 +1239,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1153,13 +1283,13 @@
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1167,7 +1297,7 @@
|
||||
},
|
||||
"/user/get_permissions": {
|
||||
"post": {
|
||||
"description": "Получить все разрашения",
|
||||
"description": "Получить все разрешения",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -1177,7 +1307,7 @@
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Получить все разрашения",
|
||||
"summary": "Получить все разрешения",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
@@ -1187,6 +1317,12 @@
|
||||
"$ref": "#/definitions/domain.Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1220,22 +1356,22 @@
|
||||
"$ref": "#/definitions/domain.AdminUserShort"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"401": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователя не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1282,13 +1418,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1335,25 +1471,25 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователь с указанным id не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1669,21 +1805,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.GrpcError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"details": {
|
||||
"type": "array",
|
||||
"items": {}
|
||||
},
|
||||
"errorCode": {
|
||||
"type": "string"
|
||||
},
|
||||
"errorMessage": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.IdRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -1861,15 +1982,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.RoleAllRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Фильтр по группе приложений",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.SecureAuthRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ type AuditResponse struct {
|
||||
}
|
||||
|
||||
type AuditPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *AuditQuery // Параметры выборки
|
||||
|
||||
@@ -26,6 +26,19 @@ var (
|
||||
ErrUnknownClient = errors.New("unknown client")
|
||||
)
|
||||
|
||||
const (
|
||||
UnknownAuditEventErrorCode = 601
|
||||
ErrOauthAuthorizationCode = 602
|
||||
ErrUnauthenticatedCode = 603
|
||||
ErrTooManyLoginRequestsCode = 604
|
||||
ErrOauthIsMissedCode = 605
|
||||
ErrAlreadyExistsCode = 606
|
||||
ErrNotFoundCode = 607
|
||||
ErrUnknownClientCode = 608
|
||||
ErrInvalidCode = 609
|
||||
ErrInvalidPasswordCode = 610
|
||||
)
|
||||
|
||||
type UnknownAuditEventError struct {
|
||||
Event string
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package domain
|
||||
|
||||
type GrpcError struct {
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Details []any `json:"details"`
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ const (
|
||||
DefaultOrderType = "desc"
|
||||
)
|
||||
|
||||
type LimitOffestParams struct {
|
||||
type LimitOffsetParams struct {
|
||||
Limit uint64 `validate:"required"` // Максимальное количество записей
|
||||
Offset uint64 // Отступ для выборки
|
||||
}
|
||||
|
||||
+24
-1
@@ -4,6 +4,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int // Идентификатор сессии
|
||||
UserId int // Идентификатор пользоватеккля
|
||||
@@ -13,7 +24,7 @@ type Session struct {
|
||||
}
|
||||
|
||||
type SessionPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *SessionQuery // Параметры выборки
|
||||
@@ -35,3 +46,15 @@ type SessionResponse struct {
|
||||
type RevokeRequest struct {
|
||||
Id int `validate:"required"` // Идентификатор сессии
|
||||
}
|
||||
|
||||
func (s Session) StatusRus() string {
|
||||
switch s.Status {
|
||||
case SessionStatusAllowed:
|
||||
return SessionStatusAllowedRus
|
||||
case SessionStatusExpired:
|
||||
return SessionStatusExpiredRus
|
||||
case SessionStatusRevoked:
|
||||
return SessionStatusRevokedRus
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ type UserQuery struct {
|
||||
}
|
||||
|
||||
type UsersPageRequest struct {
|
||||
LimitOffestParams
|
||||
LimitOffsetParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *UserQuery // Параметры выборки
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package entity
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
func AuditColumnNames() []string {
|
||||
return []string{"Пользователь", "Время события", "Действие"}
|
||||
}
|
||||
|
||||
func SessionColumnNames() []string {
|
||||
return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"}
|
||||
}
|
||||
|
||||
func UserColumnNames() []string {
|
||||
return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"}
|
||||
}
|
||||
|
||||
func RoleColumnNames() []string {
|
||||
return []string{"Действие", "Ключ в системе"}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import "time"
|
||||
type User struct {
|
||||
OauthUserId *string
|
||||
Id int64
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
FullName string
|
||||
|
||||
@@ -12,7 +12,6 @@ require (
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/sync v0.25.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -36,6 +35,7 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
@@ -79,6 +79,7 @@ require (
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/grpc v1.85.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -19,23 +19,16 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
||||
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
|
||||
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
|
||||
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
||||
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
|
||||
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
|
||||
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
@@ -45,20 +38,13 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
|
||||
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
|
||||
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
|
||||
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -66,8 +52,6 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
@@ -76,12 +60,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
@@ -90,8 +70,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -110,13 +88,10 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
|
||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
|
||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
@@ -128,9 +103,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
|
||||
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
|
||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||
@@ -138,37 +112,24 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
|
||||
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
|
||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
|
||||
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -192,14 +153,10 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
|
||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
|
||||
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
|
||||
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
@@ -213,44 +170,26 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
@@ -259,45 +198,26 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
@@ -310,14 +230,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
|
||||
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
|
||||
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
||||
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
|
||||
@@ -12,18 +12,18 @@ import (
|
||||
|
||||
var version = "1.0.0"
|
||||
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
// @license.name GNU GPL v3.0
|
||||
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
|
||||
//go:generate swag init -pd -ot json -eot json
|
||||
func main() {
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
|
||||
+159
-102
@@ -3,12 +3,12 @@ package routes
|
||||
import (
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/docs"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/common_endpoints"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
)
|
||||
|
||||
type Controllers struct {
|
||||
@@ -21,6 +21,7 @@ type Controllers struct {
|
||||
Role controller.Role
|
||||
Permissions controller.Permissions
|
||||
UiSettings controller.UiSettings
|
||||
Download controller.Download
|
||||
}
|
||||
|
||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
@@ -30,13 +31,13 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
)
|
||||
}
|
||||
|
||||
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn
|
||||
muxer := grpc.NewMux()
|
||||
func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
|
||||
muxer := router.New()
|
||||
for _, descriptor := range endpointDescriptors(c) {
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
for _, descriptor := range commonEndpoints() {
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
return muxer
|
||||
}
|
||||
@@ -45,153 +46,209 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
return []cluster.EndpointDescriptor{
|
||||
{
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
// download
|
||||
{
|
||||
Path: "user/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Users,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "session/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Sessions,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "log/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Audit,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "role/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Roles,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
requestLimit = 1000
|
||||
foundSymbol = "+"
|
||||
notFoundSymbol = "-"
|
||||
)
|
||||
|
||||
type Download struct {
|
||||
auditService Audit
|
||||
userService User
|
||||
tokenService Token
|
||||
roleService Role
|
||||
permissionService Permission
|
||||
loc *time.Location
|
||||
}
|
||||
|
||||
func NewDownload(
|
||||
auditService Audit,
|
||||
userService User,
|
||||
tokenService Token,
|
||||
roleService Role,
|
||||
permissionService Permission,
|
||||
) Download {
|
||||
loc, _ := time.LoadLocation("Europe/Moscow")
|
||||
return Download{
|
||||
auditService: auditService,
|
||||
userService: userService,
|
||||
tokenService: tokenService,
|
||||
roleService: roleService,
|
||||
permissionService: permissionService,
|
||||
loc: loc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.AuditColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write auditColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, audit := range response.Items {
|
||||
username := getUsername(userById, audit.UserId)
|
||||
|
||||
row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message}
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write audit row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.SessionColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write sessionColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, session := range response.Items {
|
||||
row := []string{
|
||||
getUsername(userById, session.UserId),
|
||||
strconv.Itoa(session.Id),
|
||||
s.formatTime(&session.CreatedAt, false),
|
||||
s.formatTime(&session.ExpiredAt, false),
|
||||
session.StatusRus()}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write session row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
users, err := s.userService.GetUsers(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
if len(users.Items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.UserColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write userColumns to csv")
|
||||
}
|
||||
|
||||
for _, user := range users.Items {
|
||||
row := []string{strconv.Itoa(int(user.Id)),
|
||||
user.FullName,
|
||||
user.Description,
|
||||
user.Email,
|
||||
getRoleNamesByIds(roles, user.Roles),
|
||||
s.formatTime(user.LastSessionCreatedAt, true)}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write user row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error {
|
||||
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
perms := s.permissionService.All(ctx)
|
||||
|
||||
if len(perms) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
columns := entity.RoleColumnNames()
|
||||
for _, role := range roles {
|
||||
columns = append(columns, role.Name)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, columns)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role columns to csv")
|
||||
}
|
||||
|
||||
for _, perm := range perms {
|
||||
row := []string{perm.Name, perm.Key}
|
||||
|
||||
for _, role := range roles {
|
||||
if slices.Contains(role.Permissions, perm.Key) {
|
||||
row = append(row, foundSymbol)
|
||||
} else {
|
||||
row = append(row, notFoundSymbol)
|
||||
}
|
||||
}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) {
|
||||
users, err := s.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
userById := make(map[int]domain.User)
|
||||
for _, user := range users.Items {
|
||||
userById[int(user.Id)] = user
|
||||
}
|
||||
|
||||
return userById, nil
|
||||
}
|
||||
|
||||
func getUsername(userById map[int]domain.User, userId int) string {
|
||||
user, ok := userById[userId]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return user.FullName
|
||||
}
|
||||
|
||||
func getRoleNamesByIds(roles []domain.Role, roleIds []int) string {
|
||||
names := make([]string, 0)
|
||||
for _, role := range roles {
|
||||
if slices.Contains(roleIds, role.Id) {
|
||||
names = append(names, role.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
func writeCsvLine(csvWriter *csv.Writer, line []string) error {
|
||||
err := csvWriter.Write(line)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write line to csv")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getCsvFileName(pageName string) string {
|
||||
return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv")
|
||||
}
|
||||
|
||||
func (s Download) formatTime(t *time.Time, onlyDate bool) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if onlyDate {
|
||||
return t.In(s.loc).Format("02-01-2006")
|
||||
}
|
||||
|
||||
return t.In(s.loc).Format("02-01-2006 15:04:05")
|
||||
}
|
||||
@@ -11,12 +11,12 @@ type Permission struct {
|
||||
permissions []domain.Permission
|
||||
}
|
||||
|
||||
func NewPermission(permissions []conf.Permission) *Permission {
|
||||
return &Permission{
|
||||
func NewPermission(permissions []conf.Permission) Permission {
|
||||
return Permission{
|
||||
permissions: toDomain(permissions),
|
||||
}
|
||||
}
|
||||
func (s *Permission) All(_ context.Context) []domain.Permission {
|
||||
func (s Permission) All(_ context.Context) []domain.Permission {
|
||||
return s.permissions
|
||||
}
|
||||
|
||||
|
||||
+28
-28
@@ -1,6 +1,7 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -12,13 +13,10 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestAuditSuite(t *testing.T) {
|
||||
@@ -31,7 +29,7 @@ type AuditSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *AuditSuite) SetupTest() {
|
||||
@@ -75,20 +73,20 @@ func (s *AuditSuite) SetupTest() {
|
||||
s.Require().NoError(err)
|
||||
s.insertAuditLogs()
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_Events_DefaultEvents() {
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
err := s.httpCli.
|
||||
Post("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]string{
|
||||
@@ -123,10 +121,10 @@ func (s *AuditSuite) Test_Events_SortEvents() {
|
||||
s.Require().NoError(err)
|
||||
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
err = s.httpCli.
|
||||
Post("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedSort := []bool{
|
||||
@@ -139,13 +137,13 @@ func (s *AuditSuite) Test_Events_SortEvents() {
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/set_events").
|
||||
err := s.httpCli.
|
||||
Post("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: entity.EventRoleChanged, Enabled: false},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]bool{
|
||||
@@ -169,16 +167,18 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||
err := s.grpcCli.Invoke("admin/log/set_events").
|
||||
err := s.httpCli.Post("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: "новый#2", Enabled: false},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
status, isStatus := status.FromError(err)
|
||||
s.Require().True(isStatus)
|
||||
s.Require().Equal(codes.InvalidArgument, status.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_All_Logs() {
|
||||
@@ -192,11 +192,11 @@ func (s *AuditSuite) Test_All_Logs() {
|
||||
}
|
||||
|
||||
var response *domain.AuditResponse
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
err := s.httpCli.
|
||||
Post("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 3)
|
||||
@@ -210,11 +210,11 @@ func (s *AuditSuite) Test_All_Logs() {
|
||||
request.Limit = 10
|
||||
request.Offset = 0
|
||||
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 6)
|
||||
|
||||
+55
-46
@@ -18,18 +18,15 @@ import (
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestAuthTestSuite(t *testing.T) {
|
||||
@@ -42,7 +39,7 @@ type AuthTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
oauthCli *httpcli.Client
|
||||
oauthClientName string
|
||||
}
|
||||
@@ -81,11 +78,11 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
mocksrv.Close()
|
||||
})
|
||||
}
|
||||
@@ -99,13 +96,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.LoginResponse{}
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -115,16 +112,18 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a1@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -138,16 +137,18 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
||||
Blocked: true,
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -160,16 +161,18 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "WrongPassword",
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -177,13 +180,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
user := entity.User{}
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
||||
@@ -199,17 +202,19 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName + fake.It[string](),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
@@ -221,9 +226,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(s.T().Context())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||
@@ -233,9 +238,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
|
||||
Do(s.T().Context())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, "0143218411981").
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
time.Sleep(time.Second)
|
||||
@@ -264,9 +269,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(s.T().Context())
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||
@@ -290,20 +295,24 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
group.Go(func() error {
|
||||
start := time.Now()
|
||||
response := domain.LoginResponse{}
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(ctx)
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
s.Require().Error(err)
|
||||
|
||||
switch status.Code(err) { // nolint:exhaustive
|
||||
case codes.ResourceExhausted:
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
|
||||
switch httpErr.StatusCode { // nolint:exhaustive
|
||||
case http.StatusTooManyRequests:
|
||||
tooManyRequestsErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) < time.Second)
|
||||
case codes.Unauthenticated:
|
||||
case http.StatusUnauthorized:
|
||||
unauthorizedErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) > time.Second)
|
||||
default:
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestCustomizationTestSuite(t *testing.T) {
|
||||
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) SetupTest() {
|
||||
@@ -44,21 +44,21 @@ func (s *CustomizationTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) TestGetDesign() {
|
||||
response := conf.UIDesign{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_design").
|
||||
err := s.httpCli.
|
||||
Post("admin/user/get_design").
|
||||
JsonRequestBody(struct{}{}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := conf.UIDesign{
|
||||
Name: "test",
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// nolint: funlen
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestDownloadSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &DownloadSuite{})
|
||||
}
|
||||
|
||||
type DownloadSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
permissions entity.PermList
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
Permissions: []conf.Permission{
|
||||
{
|
||||
Key: "data_download",
|
||||
Name: "123",
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
s.permissions = entity.PermList{
|
||||
"data_download",
|
||||
}
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestUsersHappyPath() {
|
||||
id1 := InsertUser(s.db, entity.User{
|
||||
FirstName: "Alice",
|
||||
LastName: "Bob",
|
||||
FullName: "Bob Alice",
|
||||
Email: "alice@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)})
|
||||
|
||||
resp, err := s.httpCli.Post("user/download").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["id"]
|
||||
s.Require().True(ok)
|
||||
emailIdx, ok := col["Email"]
|
||||
s.Require().True(ok)
|
||||
fullNameIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
|
||||
row := records[1]
|
||||
s.Require().EqualValues("3", row[idIdx])
|
||||
s.Require().EqualValues("alice@a.ru", row[emailIdx])
|
||||
s.Require().EqualValues("Bob Alice", row[fullNameIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestSessionsHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_1",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-1 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_2",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-2 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_3",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusExpired,
|
||||
ExpiredAt: timeNow.Add(-1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-3 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
|
||||
resp, err := s.httpCli.Post("/session/download").
|
||||
JsonRequestBody(domain.SessionPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
userIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
idIdx, ok := col["Идентификатор"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[userIdx])
|
||||
s.Require().EqualValues("1", row[idIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestAuditHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
auditRepo := repository.NewAudit(s.db)
|
||||
_, err := auditRepo.Insert(s.T().Context(), entity.Audit{
|
||||
Id: 1,
|
||||
UserId: int(userId),
|
||||
Message: "audit1@a.ru",
|
||||
Event: "123456",
|
||||
CreatedAt: timeNow,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
resp, err := s.httpCli.Post("log/download").
|
||||
JsonRequestBody(domain.AuditPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
moveIdx, ok := col["Действие"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 2)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[idIdx])
|
||||
s.Require().EqualValues("audit1@a.ru", row[moveIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestRolesHappyPath() {
|
||||
resp, err := s.httpCli.Post("role/download").
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
}
|
||||
+30
-28
@@ -1,6 +1,7 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -13,13 +14,10 @@ import (
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestRoleTestSuite(t *testing.T) {
|
||||
@@ -32,7 +30,7 @@ type RoleTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
adminId int64
|
||||
}
|
||||
|
||||
@@ -48,11 +46,11 @@ func (s *RoleTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.httpCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
@@ -79,7 +77,8 @@ func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{}, &roles))
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
groups := make(map[string]string, len(roles))
|
||||
for _, role := range roles {
|
||||
@@ -94,12 +93,10 @@ func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
|
||||
roles := []domain.Role{}
|
||||
err := s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
||||
statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
||||
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.InvalidArgument, st.Code())
|
||||
s.Require().Equal(http.StatusBadRequest, statusCode)
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
@@ -108,30 +105,34 @@ func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles))
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(roles, 1)
|
||||
s.Require().Equal("groupA", roles[0].ApplicationGroup)
|
||||
|
||||
roles = []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles))
|
||||
_, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
|
||||
role := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{
|
||||
_, err := s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group",
|
||||
Permissions: []string{},
|
||||
}, &role))
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
|
||||
roleEmpty := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{
|
||||
_, err = s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_empty",
|
||||
Permissions: []string{},
|
||||
}, &roleEmpty))
|
||||
}, &roleEmpty)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group", role.ApplicationGroup)
|
||||
@@ -146,26 +147,27 @@ func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
|
||||
})
|
||||
|
||||
role := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/update", domain.UpdateRoleRequest{
|
||||
_, err := s.request("admin/role/update", domain.UpdateRoleRequest{
|
||||
Id: int(roleId),
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group_new",
|
||||
Permissions: []string{},
|
||||
}, &role))
|
||||
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group_new", role.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) invoke(path string, req, resp any) error {
|
||||
err := s.grpcCli.Invoke(path).
|
||||
func (s *RoleTestSuite) request(path string, req, resp any) (int, error) {
|
||||
err := s.httpCli.Post(path).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(resp).
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "invoke %s", path)
|
||||
return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path)
|
||||
}
|
||||
|
||||
return nil
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
+19
-20
@@ -12,11 +12,10 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestSecureSuite(t *testing.T) {
|
||||
@@ -30,7 +29,7 @@ type SecureSuite struct {
|
||||
test *test.Test
|
||||
require *require.Assertions
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *SecureSuite) SetupTest() {
|
||||
@@ -44,11 +43,11 @@ func (s *SecureSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
|
||||
server, apiCli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.test.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
s.grpcCli = apiCli
|
||||
s.httpCli = apiCli
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
@@ -61,12 +60,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "happy_path",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: true,
|
||||
@@ -85,12 +84,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "revoked",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -109,12 +108,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "expired",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -125,12 +124,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_NotFound() {
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "not_found",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -165,35 +164,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthzResponse{}
|
||||
err := s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err := s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm1",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm2",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm3",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.False(result.Authorized)
|
||||
}
|
||||
+20
-21
@@ -14,11 +14,10 @@ import (
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestSessionSuite(t *testing.T) {
|
||||
@@ -32,7 +31,7 @@ type SessionSuite struct {
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
config assembly.Config
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *SessionSuite) SetupTest() {
|
||||
@@ -77,11 +76,11 @@ func (s *SessionSuite) SetupTest() {
|
||||
|
||||
s.config = config
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, s.config.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, cli := httpt.TestServer(s.test, config.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,11 +121,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
}
|
||||
|
||||
var response *domain.SessionResponse
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err := s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -142,11 +141,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
To: timeNow.Add(24 * time.Hour),
|
||||
},
|
||||
}
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -161,11 +160,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Type: "asc",
|
||||
}
|
||||
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 3)
|
||||
@@ -181,11 +180,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Status: []string{entity.TokenStatusExpired},
|
||||
}
|
||||
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 1)
|
||||
@@ -216,11 +215,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Id: new(2),
|
||||
},
|
||||
}
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 5)
|
||||
|
||||
+14
-13
@@ -4,23 +4,22 @@ import (
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
type UiSettingsSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
apiCli *client.Client
|
||||
apiCli *httpcli.Client
|
||||
oauthClientSetting conf.OauthClientConfig
|
||||
baseOauthUrl string
|
||||
}
|
||||
@@ -54,18 +53,18 @@ func (s *UiSettingsSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, 0)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, s.apiCli = grpct.TestServer(s.test, cfg.Handler)
|
||||
_, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
var resp domain.UiOauthSetting
|
||||
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName,
|
||||
}).
|
||||
JsonResponseBody(&resp).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
loginURL, err := url.Parse(resp.LoginUrl)
|
||||
@@ -93,13 +92,15 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
}
|
||||
+99
-83
@@ -2,11 +2,12 @@ package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
@@ -19,13 +20,10 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
@@ -42,7 +40,7 @@ type UserTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
apiCli *httpcli.Client
|
||||
httpCli *httpcli.Client
|
||||
tokenService tokenService
|
||||
}
|
||||
@@ -60,11 +58,11 @@ func (s *UserTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.apiCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
server.Close()
|
||||
})
|
||||
|
||||
tokenRep := repository.NewToken(s.db)
|
||||
@@ -90,10 +88,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
JsonResponseBody(&response).
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
Do(s.T().Context())
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -117,13 +115,14 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
Do(s.T().Context())
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.NotFound, st.Code())
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
@@ -145,11 +144,11 @@ func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -184,7 +183,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
email := "a1@"
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
@@ -198,7 +197,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
roles := []int{int(roleId1), int(roleId2)}
|
||||
@@ -210,7 +209,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
s.Require().EqualValues(roles, response.Items[1].Roles)
|
||||
|
||||
email = "test@mail.ru"
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
@@ -224,7 +223,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
s.Require().Empty(response.Items)
|
||||
}
|
||||
@@ -247,7 +246,10 @@ func (s *UserTestSuite) TestAllGetUsers() {
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context())
|
||||
err := s.apiCli.Post("admin/user/get_all_users").
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 7)
|
||||
@@ -292,7 +294,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
@@ -308,7 +310,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -326,7 +328,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
@@ -339,7 +341,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 4)
|
||||
@@ -356,9 +358,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -366,7 +368,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -384,9 +386,9 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -394,7 +396,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -407,20 +409,22 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "exists@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
@@ -432,12 +436,11 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
Email: "update@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -459,12 +462,11 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
||||
Email: "oauth@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -487,15 +489,16 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
@@ -510,15 +513,16 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
@@ -528,12 +532,12 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/delete_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.apiCli.
|
||||
Post("admin/user/delete_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(2, response.Deleted)
|
||||
@@ -559,10 +563,11 @@ func (s *UserTestSuite) TestBlockUser() {
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/user/block_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.apiCli.Post("admin/user/block_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
StatusCodeToError().
|
||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||
Do(s.T().Context())
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
|
||||
@@ -590,20 +595,31 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
||||
|
||||
// check for err when invalid data
|
||||
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
||||
err := s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err := s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(invalidReq).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
err = apierrors.FromError(err)
|
||||
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
|
||||
var body struct {
|
||||
ErrorCode int `json:"errorCode"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
|
||||
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
|
||||
|
||||
// change password
|
||||
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
||||
err = s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err = s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(changePswReq).
|
||||
Do(s.T().Context())
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
|
||||
s.Require().NoError(err)
|
||||
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
- master
|
||||
before_install:
|
||||
- go get github.com/mattn/goveralls
|
||||
script:
|
||||
- go test -v -covermode=count -coverprofile=coverage.out
|
||||
- go vet ./...
|
||||
- test -z "$(gofmt -d -s . | tee /dev/stderr)"
|
||||
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2013, Julien Schmidt
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
# HttpRouter [](https://travis-ci.org/julienschmidt/httprouter) [](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [](http://godoc.org/github.com/julienschmidt/httprouter)
|
||||
|
||||
HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/).
|
||||
|
||||
In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better.
|
||||
|
||||
The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.
|
||||
|
||||
## Features
|
||||
|
||||
**Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
|
||||
|
||||
**Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).
|
||||
|
||||
**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
|
||||
|
||||
**Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
|
||||
|
||||
**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard `Handler`/`HandlerFunc` API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.
|
||||
|
||||
**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation.
|
||||
|
||||
**No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page.
|
||||
|
||||
**Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies.
|
||||
|
||||
Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles).
|
||||
|
||||
## Usage
|
||||
|
||||
This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
|
||||
|
||||
Let's start with a trivial example:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"log"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Welcome!\n")
|
||||
}
|
||||
|
||||
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
|
||||
}
|
||||
|
||||
func main() {
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", router))
|
||||
}
|
||||
```
|
||||
|
||||
### Named parameters
|
||||
|
||||
As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrieved by `ByName("name")`.
|
||||
|
||||
When using a `http.Handler` (using `router.Handler` or `http.HandlerFunc`) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the `request.Context`. See more below under [Why doesn't this work with http.Handler?](#why-doesnt-this-work-with-httphandler).
|
||||
|
||||
Named parameters only match a single path segment:
|
||||
|
||||
```
|
||||
Pattern: /user/:user
|
||||
|
||||
/user/gordon match
|
||||
/user/you match
|
||||
/user/gordon/profile no match
|
||||
/user/ no match
|
||||
```
|
||||
|
||||
**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
|
||||
|
||||
### Catch-All parameters
|
||||
|
||||
The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern:
|
||||
|
||||
```
|
||||
Pattern: /src/*filepath
|
||||
|
||||
/src/ match
|
||||
/src/somefile.go match
|
||||
/src/subdir/somefile.go match
|
||||
```
|
||||
|
||||
## How does it work?
|
||||
|
||||
The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like:
|
||||
|
||||
```
|
||||
Priority Path Handle
|
||||
9 \ *<1>
|
||||
3 ├s nil
|
||||
2 |├earch\ *<2>
|
||||
1 |└upport\ *<3>
|
||||
2 ├blog\ *<4>
|
||||
1 | └:post nil
|
||||
1 | └\ *<5>
|
||||
2 ├about-us\ *<6>
|
||||
1 | └team\ *<7>
|
||||
1 └contact\ *<8>
|
||||
```
|
||||
|
||||
Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient.
|
||||
|
||||
Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.
|
||||
|
||||
For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:
|
||||
|
||||
1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
|
||||
2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
|
||||
|
||||
```
|
||||
├------------
|
||||
├---------
|
||||
├-----
|
||||
├----
|
||||
├--
|
||||
├--
|
||||
└-
|
||||
```
|
||||
|
||||
## Why doesn't this work with `http.Handler`?
|
||||
|
||||
**It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.
|
||||
|
||||
Named parameters can be accessed `request.Context`:
|
||||
|
||||
```go
|
||||
func Hello(w http.ResponseWriter, r *http.Request) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
|
||||
fmt.Fprintf(w, "hello, %s!\n", params.ByName("name"))
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, one can also use `params := r.Context().Value(httprouter.ParamsKey)` instead of the helper function.
|
||||
|
||||
Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
|
||||
|
||||
## Automatic OPTIONS responses and CORS
|
||||
|
||||
One might wish to modify automatic responses to OPTIONS requests, e.g. to support [CORS preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/preflight_request) or to set other headers.
|
||||
This can be achieved using the [`Router.GlobalOPTIONS`](https://godoc.org/github.com/julienschmidt/httprouter#Router.GlobalOPTIONS) handler:
|
||||
|
||||
```go
|
||||
router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
// Set CORS headers
|
||||
header := w.Header()
|
||||
header.Set("Access-Control-Allow-Methods", r.Header.Get("Allow"))
|
||||
header.Set("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
|
||||
// Adjust status code to 204
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
```
|
||||
|
||||
## Where can I find Middleware *X*?
|
||||
|
||||
This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`](https://golang.org/pkg/net/http/#Handler), you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy!
|
||||
|
||||
Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).
|
||||
|
||||
### Multi-domain / Sub-domains
|
||||
|
||||
Here is a quick example: Does your server serve multiple domains / hosts?
|
||||
You want to use sub-domains?
|
||||
Define a router per host!
|
||||
|
||||
```go
|
||||
// We need an object that implements the http.Handler interface.
|
||||
// Therefore we need a type for which we implement the ServeHTTP method.
|
||||
// We just use a map here, in which we map host names (with port) to http.Handlers
|
||||
type HostSwitch map[string]http.Handler
|
||||
|
||||
// Implement the ServeHTTP method on our new type
|
||||
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if a http.Handler is registered for the given host.
|
||||
// If yes, use it to handle the request.
|
||||
if handler := hs[r.Host]; handler != nil {
|
||||
handler.ServeHTTP(w, r)
|
||||
} else {
|
||||
// Handle host names for which no handler is registered
|
||||
http.Error(w, "Forbidden", 403) // Or Redirect?
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Initialize a router as usual
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
// Make a new HostSwitch and insert the router (our http handler)
|
||||
// for example.com and port 12345
|
||||
hs := make(HostSwitch)
|
||||
hs["example.com:12345"] = router
|
||||
|
||||
// Use the HostSwitch to listen and serve on port 12345
|
||||
log.Fatal(http.ListenAndServe(":12345", hs))
|
||||
}
|
||||
```
|
||||
|
||||
### Basic Authentication
|
||||
|
||||
Another quick example: Basic Authentication (RFC 2617) for handles:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
// Get the Basic Authentication credentials
|
||||
user, password, hasAuth := r.BasicAuth()
|
||||
|
||||
if hasAuth && user == requiredUser && password == requiredPassword {
|
||||
// Delegate request to the given handle
|
||||
h(w, r, ps)
|
||||
} else {
|
||||
// Request Basic Authentication otherwise
|
||||
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
|
||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Not protected!\n")
|
||||
}
|
||||
|
||||
func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Protected!\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
user := "gordon"
|
||||
pass := "secret!"
|
||||
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/protected/", BasicAuth(Protected, user, pass))
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", router))
|
||||
}
|
||||
```
|
||||
|
||||
## Chaining with the NotFound handler
|
||||
|
||||
**NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**
|
||||
|
||||
You can use another [`http.Handler`](https://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining.
|
||||
|
||||
### Static files
|
||||
|
||||
The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets):
|
||||
|
||||
```go
|
||||
// Serve static files from the ./public directory
|
||||
router.NotFound = http.FileServer(http.Dir("public"))
|
||||
```
|
||||
|
||||
But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`.
|
||||
|
||||
## Web Frameworks based on HttpRouter
|
||||
|
||||
If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
|
||||
|
||||
* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework
|
||||
* [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go
|
||||
* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
|
||||
* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go
|
||||
* [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain
|
||||
* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
|
||||
* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow
|
||||
* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support
|
||||
* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context
|
||||
* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba
|
||||
* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang
|
||||
* [pbgo](https://github.com/chai2010/pbgo): pbgo is a mini RPC/REST framework based on Protobuf
|
||||
* [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server
|
||||
* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts
|
||||
* [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware)
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Based on the path package, Copyright 2009 The Go Authors.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
package httprouter
|
||||
|
||||
// CleanPath is the URL version of path.Clean, it returns a canonical URL path
|
||||
// for p, eliminating . and .. elements.
|
||||
//
|
||||
// The following rules are applied iteratively until no further processing can
|
||||
// be done:
|
||||
// 1. Replace multiple slashes with a single slash.
|
||||
// 2. Eliminate each . path name element (the current directory).
|
||||
// 3. Eliminate each inner .. path name element (the parent directory)
|
||||
// along with the non-.. element that precedes it.
|
||||
// 4. Eliminate .. elements that begin a rooted path:
|
||||
// that is, replace "/.." by "/" at the beginning of a path.
|
||||
//
|
||||
// If the result of this process is an empty string, "/" is returned
|
||||
func CleanPath(p string) string {
|
||||
// Turn empty string into "/"
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
|
||||
n := len(p)
|
||||
var buf []byte
|
||||
|
||||
// Invariants:
|
||||
// reading from path; r is index of next byte to process.
|
||||
// writing to buf; w is index of next byte to write.
|
||||
|
||||
// path must start with '/'
|
||||
r := 1
|
||||
w := 1
|
||||
|
||||
if p[0] != '/' {
|
||||
r = 0
|
||||
buf = make([]byte, n+1)
|
||||
buf[0] = '/'
|
||||
}
|
||||
|
||||
trailing := n > 1 && p[n-1] == '/'
|
||||
|
||||
// A bit more clunky without a 'lazybuf' like the path package, but the loop
|
||||
// gets completely inlined (bufApp). So in contrast to the path package this
|
||||
// loop has no expensive function calls (except 1x make)
|
||||
|
||||
for r < n {
|
||||
switch {
|
||||
case p[r] == '/':
|
||||
// empty path element, trailing slash is added after the end
|
||||
r++
|
||||
|
||||
case p[r] == '.' && r+1 == n:
|
||||
trailing = true
|
||||
r++
|
||||
|
||||
case p[r] == '.' && p[r+1] == '/':
|
||||
// . element
|
||||
r += 2
|
||||
|
||||
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
|
||||
// .. element: remove to last /
|
||||
r += 3
|
||||
|
||||
if w > 1 {
|
||||
// can backtrack
|
||||
w--
|
||||
|
||||
if buf == nil {
|
||||
for w > 1 && p[w] != '/' {
|
||||
w--
|
||||
}
|
||||
} else {
|
||||
for w > 1 && buf[w] != '/' {
|
||||
w--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
// real path element.
|
||||
// add slash if needed
|
||||
if w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
// copy element
|
||||
for r < n && p[r] != '/' {
|
||||
bufApp(&buf, p, w, p[r])
|
||||
w++
|
||||
r++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// re-append trailing slash
|
||||
if trailing && w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
if buf == nil {
|
||||
return p[:w]
|
||||
}
|
||||
return string(buf[:w])
|
||||
}
|
||||
|
||||
// internal helper to lazily create a buffer if necessary
|
||||
func bufApp(buf *[]byte, s string, w int, c byte) {
|
||||
if *buf == nil {
|
||||
if s[w] == c {
|
||||
return
|
||||
}
|
||||
|
||||
*buf = make([]byte, len(s))
|
||||
copy(*buf, s[:w])
|
||||
}
|
||||
(*buf)[w] = c
|
||||
}
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
// Package httprouter is a trie based high performance HTTP request router.
|
||||
//
|
||||
// A trivial example is:
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// import (
|
||||
// "fmt"
|
||||
// "github.com/julienschmidt/httprouter"
|
||||
// "net/http"
|
||||
// "log"
|
||||
// )
|
||||
//
|
||||
// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
// fmt.Fprint(w, "Welcome!\n")
|
||||
// }
|
||||
//
|
||||
// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
|
||||
// }
|
||||
//
|
||||
// func main() {
|
||||
// router := httprouter.New()
|
||||
// router.GET("/", Index)
|
||||
// router.GET("/hello/:name", Hello)
|
||||
//
|
||||
// log.Fatal(http.ListenAndServe(":8080", router))
|
||||
// }
|
||||
//
|
||||
// The router matches incoming requests by the request method and the path.
|
||||
// If a handle is registered for this path and method, the router delegates the
|
||||
// request to that function.
|
||||
// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
|
||||
// register handles, for all other methods router.Handle can be used.
|
||||
//
|
||||
// The registered path, against which the router matches incoming requests, can
|
||||
// contain two types of parameters:
|
||||
// Syntax Type
|
||||
// :name named parameter
|
||||
// *name catch-all parameter
|
||||
//
|
||||
// Named parameters are dynamic path segments. They match anything until the
|
||||
// next '/' or the path end:
|
||||
// Path: /blog/:category/:post
|
||||
//
|
||||
// Requests:
|
||||
// /blog/go/request-routers match: category="go", post="request-routers"
|
||||
// /blog/go/request-routers/ no match, but the router would redirect
|
||||
// /blog/go/ no match
|
||||
// /blog/go/request-routers/comments no match
|
||||
//
|
||||
// Catch-all parameters match anything until the path end, including the
|
||||
// directory index (the '/' before the catch-all). Since they match anything
|
||||
// until the end, catch-all parameters must always be the final path element.
|
||||
// Path: /files/*filepath
|
||||
//
|
||||
// Requests:
|
||||
// /files/ match: filepath="/"
|
||||
// /files/LICENSE match: filepath="/LICENSE"
|
||||
// /files/templates/article.html match: filepath="/templates/article.html"
|
||||
// /files no match, but the router would redirect
|
||||
//
|
||||
// The value of parameters is saved as a slice of the Param struct, consisting
|
||||
// each of a key and a value. The slice is passed to the Handle func as a third
|
||||
// parameter.
|
||||
// There are two ways to retrieve the value of a parameter:
|
||||
// // by the name of the parameter
|
||||
// user := ps.ByName("user") // defined by :user or *user
|
||||
//
|
||||
// // by the index of the parameter. This way you can also get the name (key)
|
||||
// thirdKey := ps[2].Key // the name of the 3rd parameter
|
||||
// thirdValue := ps[2].Value // the value of the 3rd parameter
|
||||
package httprouter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Handle is a function that can be registered to a route to handle HTTP
|
||||
// requests. Like http.HandlerFunc, but has a third parameter for the values of
|
||||
// wildcards (variables).
|
||||
type Handle func(http.ResponseWriter, *http.Request, Params)
|
||||
|
||||
// Param is a single URL parameter, consisting of a key and a value.
|
||||
type Param struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
// Params is a Param-slice, as returned by the router.
|
||||
// The slice is ordered, the first URL parameter is also the first slice value.
|
||||
// It is therefore safe to read values by the index.
|
||||
type Params []Param
|
||||
|
||||
// ByName returns the value of the first Param which key matches the given name.
|
||||
// If no matching Param is found, an empty string is returned.
|
||||
func (ps Params) ByName(name string) string {
|
||||
for i := range ps {
|
||||
if ps[i].Key == name {
|
||||
return ps[i].Value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type paramsKey struct{}
|
||||
|
||||
// ParamsKey is the request context key under which URL params are stored.
|
||||
var ParamsKey = paramsKey{}
|
||||
|
||||
// ParamsFromContext pulls the URL parameters from a request context,
|
||||
// or returns nil if none are present.
|
||||
func ParamsFromContext(ctx context.Context) Params {
|
||||
p, _ := ctx.Value(ParamsKey).(Params)
|
||||
return p
|
||||
}
|
||||
|
||||
// Router is a http.Handler which can be used to dispatch requests to different
|
||||
// handler functions via configurable routes
|
||||
type Router struct {
|
||||
trees map[string]*node
|
||||
|
||||
// Enables automatic redirection if the current route can't be matched but a
|
||||
// handler for the path with (without) the trailing slash exists.
|
||||
// For example if /foo/ is requested but a route only exists for /foo, the
|
||||
// client is redirected to /foo with http status code 301 for GET requests
|
||||
// and 307 for all other request methods.
|
||||
RedirectTrailingSlash bool
|
||||
|
||||
// If enabled, the router tries to fix the current request path, if no
|
||||
// handle is registered for it.
|
||||
// First superfluous path elements like ../ or // are removed.
|
||||
// Afterwards the router does a case-insensitive lookup of the cleaned path.
|
||||
// If a handle can be found for this route, the router makes a redirection
|
||||
// to the corrected path with status code 301 for GET requests and 307 for
|
||||
// all other request methods.
|
||||
// For example /FOO and /..//Foo could be redirected to /foo.
|
||||
// RedirectTrailingSlash is independent of this option.
|
||||
RedirectFixedPath bool
|
||||
|
||||
// If enabled, the router checks if another method is allowed for the
|
||||
// current route, if the current request can not be routed.
|
||||
// If this is the case, the request is answered with 'Method Not Allowed'
|
||||
// and HTTP status code 405.
|
||||
// If no other Method is allowed, the request is delegated to the NotFound
|
||||
// handler.
|
||||
HandleMethodNotAllowed bool
|
||||
|
||||
// If enabled, the router automatically replies to OPTIONS requests.
|
||||
// Custom OPTIONS handlers take priority over automatic replies.
|
||||
HandleOPTIONS bool
|
||||
|
||||
// An optional http.Handler that is called on automatic OPTIONS requests.
|
||||
// The handler is only called if HandleOPTIONS is true and no OPTIONS
|
||||
// handler for the specific path was set.
|
||||
// The "Allowed" header is set before calling the handler.
|
||||
GlobalOPTIONS http.Handler
|
||||
|
||||
// Cached value of global (*) allowed methods
|
||||
globalAllowed string
|
||||
|
||||
// Configurable http.Handler which is called when no matching route is
|
||||
// found. If it is not set, http.NotFound is used.
|
||||
NotFound http.Handler
|
||||
|
||||
// Configurable http.Handler which is called when a request
|
||||
// cannot be routed and HandleMethodNotAllowed is true.
|
||||
// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
|
||||
// The "Allow" header with allowed request methods is set before the handler
|
||||
// is called.
|
||||
MethodNotAllowed http.Handler
|
||||
|
||||
// Function to handle panics recovered from http handlers.
|
||||
// It should be used to generate a error page and return the http error code
|
||||
// 500 (Internal Server Error).
|
||||
// The handler can be used to keep your server from crashing because of
|
||||
// unrecovered panics.
|
||||
PanicHandler func(http.ResponseWriter, *http.Request, interface{})
|
||||
}
|
||||
|
||||
// Make sure the Router conforms with the http.Handler interface
|
||||
var _ http.Handler = New()
|
||||
|
||||
// New returns a new initialized Router.
|
||||
// Path auto-correction, including trailing slashes, is enabled by default.
|
||||
func New() *Router {
|
||||
return &Router{
|
||||
RedirectTrailingSlash: true,
|
||||
RedirectFixedPath: true,
|
||||
HandleMethodNotAllowed: true,
|
||||
HandleOPTIONS: true,
|
||||
}
|
||||
}
|
||||
|
||||
// GET is a shortcut for router.Handle(http.MethodGet, path, handle)
|
||||
func (r *Router) GET(path string, handle Handle) {
|
||||
r.Handle(http.MethodGet, path, handle)
|
||||
}
|
||||
|
||||
// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)
|
||||
func (r *Router) HEAD(path string, handle Handle) {
|
||||
r.Handle(http.MethodHead, path, handle)
|
||||
}
|
||||
|
||||
// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)
|
||||
func (r *Router) OPTIONS(path string, handle Handle) {
|
||||
r.Handle(http.MethodOptions, path, handle)
|
||||
}
|
||||
|
||||
// POST is a shortcut for router.Handle(http.MethodPost, path, handle)
|
||||
func (r *Router) POST(path string, handle Handle) {
|
||||
r.Handle(http.MethodPost, path, handle)
|
||||
}
|
||||
|
||||
// PUT is a shortcut for router.Handle(http.MethodPut, path, handle)
|
||||
func (r *Router) PUT(path string, handle Handle) {
|
||||
r.Handle(http.MethodPut, path, handle)
|
||||
}
|
||||
|
||||
// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)
|
||||
func (r *Router) PATCH(path string, handle Handle) {
|
||||
r.Handle(http.MethodPatch, path, handle)
|
||||
}
|
||||
|
||||
// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)
|
||||
func (r *Router) DELETE(path string, handle Handle) {
|
||||
r.Handle(http.MethodDelete, path, handle)
|
||||
}
|
||||
|
||||
// Handle registers a new request handle with the given path and method.
|
||||
//
|
||||
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
|
||||
// functions can be used.
|
||||
//
|
||||
// This function is intended for bulk loading and to allow the usage of less
|
||||
// frequently used, non-standardized or custom methods (e.g. for internal
|
||||
// communication with a proxy).
|
||||
func (r *Router) Handle(method, path string, handle Handle) {
|
||||
if len(path) < 1 || path[0] != '/' {
|
||||
panic("path must begin with '/' in path '" + path + "'")
|
||||
}
|
||||
|
||||
if r.trees == nil {
|
||||
r.trees = make(map[string]*node)
|
||||
}
|
||||
|
||||
root := r.trees[method]
|
||||
if root == nil {
|
||||
root = new(node)
|
||||
r.trees[method] = root
|
||||
|
||||
r.globalAllowed = r.allowed("*", "")
|
||||
}
|
||||
|
||||
root.addRoute(path, handle)
|
||||
}
|
||||
|
||||
// Handler is an adapter which allows the usage of an http.Handler as a
|
||||
// request handle.
|
||||
// The Params are available in the request context under ParamsKey.
|
||||
func (r *Router) Handler(method, path string, handler http.Handler) {
|
||||
r.Handle(method, path,
|
||||
func(w http.ResponseWriter, req *http.Request, p Params) {
|
||||
if len(p) > 0 {
|
||||
ctx := req.Context()
|
||||
ctx = context.WithValue(ctx, ParamsKey, p)
|
||||
req = req.WithContext(ctx)
|
||||
}
|
||||
handler.ServeHTTP(w, req)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
|
||||
// request handle.
|
||||
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
|
||||
r.Handler(method, path, handler)
|
||||
}
|
||||
|
||||
// ServeFiles serves files from the given file system root.
|
||||
// The path must end with "/*filepath", files are then served from the local
|
||||
// path /defined/root/dir/*filepath.
|
||||
// For example if root is "/etc" and *filepath is "passwd", the local file
|
||||
// "/etc/passwd" would be served.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use http.Dir:
|
||||
// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
|
||||
func (r *Router) ServeFiles(path string, root http.FileSystem) {
|
||||
if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
|
||||
panic("path must end with /*filepath in path '" + path + "'")
|
||||
}
|
||||
|
||||
fileServer := http.FileServer(root)
|
||||
|
||||
r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
|
||||
req.URL.Path = ps.ByName("filepath")
|
||||
fileServer.ServeHTTP(w, req)
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
|
||||
if rcv := recover(); rcv != nil {
|
||||
r.PanicHandler(w, req, rcv)
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup allows the manual lookup of a method + path combo.
|
||||
// This is e.g. useful to build a framework around this router.
|
||||
// If the path was found, it returns the handle function and the path parameter
|
||||
// values. Otherwise the third return value indicates whether a redirection to
|
||||
// the same path with an extra / without the trailing slash should be performed.
|
||||
func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
|
||||
if root := r.trees[method]; root != nil {
|
||||
return root.getValue(path)
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
func (r *Router) allowed(path, reqMethod string) (allow string) {
|
||||
allowed := make([]string, 0, 9)
|
||||
|
||||
if path == "*" { // server-wide
|
||||
// empty method is used for internal calls to refresh the cache
|
||||
if reqMethod == "" {
|
||||
for method := range r.trees {
|
||||
if method == http.MethodOptions {
|
||||
continue
|
||||
}
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, method)
|
||||
}
|
||||
} else {
|
||||
return r.globalAllowed
|
||||
}
|
||||
} else { // specific path
|
||||
for method := range r.trees {
|
||||
// Skip the requested method - we already tried this one
|
||||
if method == reqMethod || method == http.MethodOptions {
|
||||
continue
|
||||
}
|
||||
|
||||
handle, _, _ := r.trees[method].getValue(path)
|
||||
if handle != nil {
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, method)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(allowed) > 0 {
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, http.MethodOptions)
|
||||
|
||||
// Sort allowed methods.
|
||||
// sort.Strings(allowed) unfortunately causes unnecessary allocations
|
||||
// due to allowed being moved to the heap and interface conversion
|
||||
for i, l := 1, len(allowed); i < l; i++ {
|
||||
for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
|
||||
allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
|
||||
}
|
||||
}
|
||||
|
||||
// return as comma separated list
|
||||
return strings.Join(allowed, ", ")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ServeHTTP makes the router implement the http.Handler interface.
|
||||
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
if r.PanicHandler != nil {
|
||||
defer r.recv(w, req)
|
||||
}
|
||||
|
||||
path := req.URL.Path
|
||||
|
||||
if root := r.trees[req.Method]; root != nil {
|
||||
if handle, ps, tsr := root.getValue(path); handle != nil {
|
||||
handle(w, req, ps)
|
||||
return
|
||||
} else if req.Method != http.MethodConnect && path != "/" {
|
||||
code := 301 // Permanent redirect, request with GET method
|
||||
if req.Method != http.MethodGet {
|
||||
// Temporary redirect, request with same method
|
||||
// As of Go 1.3, Go does not support status code 308.
|
||||
code = 307
|
||||
}
|
||||
|
||||
if tsr && r.RedirectTrailingSlash {
|
||||
if len(path) > 1 && path[len(path)-1] == '/' {
|
||||
req.URL.Path = path[:len(path)-1]
|
||||
} else {
|
||||
req.URL.Path = path + "/"
|
||||
}
|
||||
http.Redirect(w, req, req.URL.String(), code)
|
||||
return
|
||||
}
|
||||
|
||||
// Try to fix the request path
|
||||
if r.RedirectFixedPath {
|
||||
fixedPath, found := root.findCaseInsensitivePath(
|
||||
CleanPath(path),
|
||||
r.RedirectTrailingSlash,
|
||||
)
|
||||
if found {
|
||||
req.URL.Path = string(fixedPath)
|
||||
http.Redirect(w, req, req.URL.String(), code)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if req.Method == http.MethodOptions && r.HandleOPTIONS {
|
||||
// Handle OPTIONS requests
|
||||
if allow := r.allowed(path, http.MethodOptions); allow != "" {
|
||||
w.Header().Set("Allow", allow)
|
||||
if r.GlobalOPTIONS != nil {
|
||||
r.GlobalOPTIONS.ServeHTTP(w, req)
|
||||
}
|
||||
return
|
||||
}
|
||||
} else if r.HandleMethodNotAllowed { // Handle 405
|
||||
if allow := r.allowed(path, req.Method); allow != "" {
|
||||
w.Header().Set("Allow", allow)
|
||||
if r.MethodNotAllowed != nil {
|
||||
r.MethodNotAllowed.ServeHTTP(w, req)
|
||||
} else {
|
||||
http.Error(w,
|
||||
http.StatusText(http.StatusMethodNotAllowed),
|
||||
http.StatusMethodNotAllowed,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 404
|
||||
if r.NotFound != nil {
|
||||
r.NotFound.ServeHTTP(w, req)
|
||||
} else {
|
||||
http.NotFound(w, req)
|
||||
}
|
||||
}
|
||||
+666
@@ -0,0 +1,666 @@
|
||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
package httprouter
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func min(a, b int) int {
|
||||
if a <= b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
const maxParamCount uint8 = ^uint8(0)
|
||||
|
||||
func countParams(path string) uint8 {
|
||||
var n uint
|
||||
for i := 0; i < len(path); i++ {
|
||||
if path[i] != ':' && path[i] != '*' {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
}
|
||||
if n >= uint(maxParamCount) {
|
||||
return maxParamCount
|
||||
}
|
||||
|
||||
return uint8(n)
|
||||
}
|
||||
|
||||
type nodeType uint8
|
||||
|
||||
const (
|
||||
static nodeType = iota // default
|
||||
root
|
||||
param
|
||||
catchAll
|
||||
)
|
||||
|
||||
type node struct {
|
||||
path string
|
||||
wildChild bool
|
||||
nType nodeType
|
||||
maxParams uint8
|
||||
priority uint32
|
||||
indices string
|
||||
children []*node
|
||||
handle Handle
|
||||
}
|
||||
|
||||
// increments priority of the given child and reorders if necessary
|
||||
func (n *node) incrementChildPrio(pos int) int {
|
||||
n.children[pos].priority++
|
||||
prio := n.children[pos].priority
|
||||
|
||||
// adjust position (move to front)
|
||||
newPos := pos
|
||||
for newPos > 0 && n.children[newPos-1].priority < prio {
|
||||
// swap node positions
|
||||
n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
|
||||
|
||||
newPos--
|
||||
}
|
||||
|
||||
// build new index char string
|
||||
if newPos != pos {
|
||||
n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
|
||||
n.indices[pos:pos+1] + // the index char we move
|
||||
n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
|
||||
}
|
||||
|
||||
return newPos
|
||||
}
|
||||
|
||||
// addRoute adds a node with the given handle to the path.
|
||||
// Not concurrency-safe!
|
||||
func (n *node) addRoute(path string, handle Handle) {
|
||||
fullPath := path
|
||||
n.priority++
|
||||
numParams := countParams(path)
|
||||
|
||||
// non-empty tree
|
||||
if len(n.path) > 0 || len(n.children) > 0 {
|
||||
walk:
|
||||
for {
|
||||
// Update maxParams of the current node
|
||||
if numParams > n.maxParams {
|
||||
n.maxParams = numParams
|
||||
}
|
||||
|
||||
// Find the longest common prefix.
|
||||
// This also implies that the common prefix contains no ':' or '*'
|
||||
// since the existing key can't contain those chars.
|
||||
i := 0
|
||||
max := min(len(path), len(n.path))
|
||||
for i < max && path[i] == n.path[i] {
|
||||
i++
|
||||
}
|
||||
|
||||
// Split edge
|
||||
if i < len(n.path) {
|
||||
child := node{
|
||||
path: n.path[i:],
|
||||
wildChild: n.wildChild,
|
||||
nType: static,
|
||||
indices: n.indices,
|
||||
children: n.children,
|
||||
handle: n.handle,
|
||||
priority: n.priority - 1,
|
||||
}
|
||||
|
||||
// Update maxParams (max of all children)
|
||||
for i := range child.children {
|
||||
if child.children[i].maxParams > child.maxParams {
|
||||
child.maxParams = child.children[i].maxParams
|
||||
}
|
||||
}
|
||||
|
||||
n.children = []*node{&child}
|
||||
// []byte for proper unicode char conversion, see #65
|
||||
n.indices = string([]byte{n.path[i]})
|
||||
n.path = path[:i]
|
||||
n.handle = nil
|
||||
n.wildChild = false
|
||||
}
|
||||
|
||||
// Make new node a child of this node
|
||||
if i < len(path) {
|
||||
path = path[i:]
|
||||
|
||||
if n.wildChild {
|
||||
n = n.children[0]
|
||||
n.priority++
|
||||
|
||||
// Update maxParams of the child node
|
||||
if numParams > n.maxParams {
|
||||
n.maxParams = numParams
|
||||
}
|
||||
numParams--
|
||||
|
||||
// Check if the wildcard matches
|
||||
if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
|
||||
// Adding a child to a catchAll is not possible
|
||||
n.nType != catchAll &&
|
||||
// Check for longer wildcard, e.g. :name and :names
|
||||
(len(n.path) >= len(path) || path[len(n.path)] == '/') {
|
||||
continue walk
|
||||
} else {
|
||||
// Wildcard conflict
|
||||
var pathSeg string
|
||||
if n.nType == catchAll {
|
||||
pathSeg = path
|
||||
} else {
|
||||
pathSeg = strings.SplitN(path, "/", 2)[0]
|
||||
}
|
||||
prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
|
||||
panic("'" + pathSeg +
|
||||
"' in new path '" + fullPath +
|
||||
"' conflicts with existing wildcard '" + n.path +
|
||||
"' in existing prefix '" + prefix +
|
||||
"'")
|
||||
}
|
||||
}
|
||||
|
||||
c := path[0]
|
||||
|
||||
// slash after param
|
||||
if n.nType == param && c == '/' && len(n.children) == 1 {
|
||||
n = n.children[0]
|
||||
n.priority++
|
||||
continue walk
|
||||
}
|
||||
|
||||
// Check if a child with the next path byte exists
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if c == n.indices[i] {
|
||||
i = n.incrementChildPrio(i)
|
||||
n = n.children[i]
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise insert it
|
||||
if c != ':' && c != '*' {
|
||||
// []byte for proper unicode char conversion, see #65
|
||||
n.indices += string([]byte{c})
|
||||
child := &node{
|
||||
maxParams: numParams,
|
||||
}
|
||||
n.children = append(n.children, child)
|
||||
n.incrementChildPrio(len(n.indices) - 1)
|
||||
n = child
|
||||
}
|
||||
n.insertChild(numParams, path, fullPath, handle)
|
||||
return
|
||||
|
||||
} else if i == len(path) { // Make node a (in-path) leaf
|
||||
if n.handle != nil {
|
||||
panic("a handle is already registered for path '" + fullPath + "'")
|
||||
}
|
||||
n.handle = handle
|
||||
}
|
||||
return
|
||||
}
|
||||
} else { // Empty tree
|
||||
n.insertChild(numParams, path, fullPath, handle)
|
||||
n.nType = root
|
||||
}
|
||||
}
|
||||
|
||||
func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) {
|
||||
var offset int // already handled bytes of the path
|
||||
|
||||
// find prefix until first wildcard (beginning with ':'' or '*'')
|
||||
for i, max := 0, len(path); numParams > 0; i++ {
|
||||
c := path[i]
|
||||
if c != ':' && c != '*' {
|
||||
continue
|
||||
}
|
||||
|
||||
// find wildcard end (either '/' or path end)
|
||||
end := i + 1
|
||||
for end < max && path[end] != '/' {
|
||||
switch path[end] {
|
||||
// the wildcard name must not contain ':' and '*'
|
||||
case ':', '*':
|
||||
panic("only one wildcard per path segment is allowed, has: '" +
|
||||
path[i:] + "' in path '" + fullPath + "'")
|
||||
default:
|
||||
end++
|
||||
}
|
||||
}
|
||||
|
||||
// check if this Node existing children which would be
|
||||
// unreachable if we insert the wildcard here
|
||||
if len(n.children) > 0 {
|
||||
panic("wildcard route '" + path[i:end] +
|
||||
"' conflicts with existing children in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
// check if the wildcard has a name
|
||||
if end-i < 2 {
|
||||
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
if c == ':' { // param
|
||||
// split path at the beginning of the wildcard
|
||||
if i > 0 {
|
||||
n.path = path[offset:i]
|
||||
offset = i
|
||||
}
|
||||
|
||||
child := &node{
|
||||
nType: param,
|
||||
maxParams: numParams,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n.wildChild = true
|
||||
n = child
|
||||
n.priority++
|
||||
numParams--
|
||||
|
||||
// if the path doesn't end with the wildcard, then there
|
||||
// will be another non-wildcard subpath starting with '/'
|
||||
if end < max {
|
||||
n.path = path[offset:end]
|
||||
offset = end
|
||||
|
||||
child := &node{
|
||||
maxParams: numParams,
|
||||
priority: 1,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n = child
|
||||
}
|
||||
|
||||
} else { // catchAll
|
||||
if end != max || numParams > 1 {
|
||||
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
|
||||
panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
// currently fixed width 1 for '/'
|
||||
i--
|
||||
if path[i] != '/' {
|
||||
panic("no / before catch-all in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
n.path = path[offset:i]
|
||||
|
||||
// first node: catchAll node with empty path
|
||||
child := &node{
|
||||
wildChild: true,
|
||||
nType: catchAll,
|
||||
maxParams: 1,
|
||||
}
|
||||
// update maxParams of the parent node
|
||||
if n.maxParams < 1 {
|
||||
n.maxParams = 1
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n.indices = string(path[i])
|
||||
n = child
|
||||
n.priority++
|
||||
|
||||
// second node: node holding the variable
|
||||
child = &node{
|
||||
path: path[i:],
|
||||
nType: catchAll,
|
||||
maxParams: 1,
|
||||
handle: handle,
|
||||
priority: 1,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// insert remaining path part and handle to the leaf
|
||||
n.path = path[offset:]
|
||||
n.handle = handle
|
||||
}
|
||||
|
||||
// Returns the handle registered with the given path (key). The values of
|
||||
// wildcards are saved to a map.
|
||||
// If no handle can be found, a TSR (trailing slash redirect) recommendation is
|
||||
// made if a handle exists with an extra (without the) trailing slash for the
|
||||
// given path.
|
||||
func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) {
|
||||
walk: // outer loop for walking the tree
|
||||
for {
|
||||
if len(path) > len(n.path) {
|
||||
if path[:len(n.path)] == n.path {
|
||||
path = path[len(n.path):]
|
||||
// If this node does not have a wildcard (param or catchAll)
|
||||
// child, we can just look up the next child node and continue
|
||||
// to walk down the tree
|
||||
if !n.wildChild {
|
||||
c := path[0]
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if c == n.indices[i] {
|
||||
n = n.children[i]
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found.
|
||||
// We can recommend to redirect to the same URL without a
|
||||
// trailing slash if a leaf exists for that path.
|
||||
tsr = (path == "/" && n.handle != nil)
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// handle wildcard child
|
||||
n = n.children[0]
|
||||
switch n.nType {
|
||||
case param:
|
||||
// find param end (either '/' or path end)
|
||||
end := 0
|
||||
for end < len(path) && path[end] != '/' {
|
||||
end++
|
||||
}
|
||||
|
||||
// save param value
|
||||
if p == nil {
|
||||
// lazy allocation
|
||||
p = make(Params, 0, n.maxParams)
|
||||
}
|
||||
i := len(p)
|
||||
p = p[:i+1] // expand slice within preallocated capacity
|
||||
p[i].Key = n.path[1:]
|
||||
p[i].Value = path[:end]
|
||||
|
||||
// we need to go deeper!
|
||||
if end < len(path) {
|
||||
if len(n.children) > 0 {
|
||||
path = path[end:]
|
||||
n = n.children[0]
|
||||
continue walk
|
||||
}
|
||||
|
||||
// ... but we can't
|
||||
tsr = (len(path) == end+1)
|
||||
return
|
||||
}
|
||||
|
||||
if handle = n.handle; handle != nil {
|
||||
return
|
||||
} else if len(n.children) == 1 {
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists for TSR recommendation
|
||||
n = n.children[0]
|
||||
tsr = (n.path == "/" && n.handle != nil)
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
case catchAll:
|
||||
// save param value
|
||||
if p == nil {
|
||||
// lazy allocation
|
||||
p = make(Params, 0, n.maxParams)
|
||||
}
|
||||
i := len(p)
|
||||
p = p[:i+1] // expand slice within preallocated capacity
|
||||
p[i].Key = n.path[2:]
|
||||
p[i].Value = path
|
||||
|
||||
handle = n.handle
|
||||
return
|
||||
|
||||
default:
|
||||
panic("invalid node type")
|
||||
}
|
||||
}
|
||||
} else if path == n.path {
|
||||
// We should have reached the node containing the handle.
|
||||
// Check if this node has a handle registered.
|
||||
if handle = n.handle; handle != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if path == "/" && n.wildChild && n.nType != root {
|
||||
tsr = true
|
||||
return
|
||||
}
|
||||
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists for trailing slash recommendation
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == '/' {
|
||||
n = n.children[i]
|
||||
tsr = (len(n.path) == 1 && n.handle != nil) ||
|
||||
(n.nType == catchAll && n.children[0].handle != nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Nothing found. We can recommend to redirect to the same URL with an
|
||||
// extra trailing slash if a leaf exists for that path
|
||||
tsr = (path == "/") ||
|
||||
(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
|
||||
path == n.path[:len(n.path)-1] && n.handle != nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Makes a case-insensitive lookup of the given path and tries to find a handler.
|
||||
// It can optionally also fix trailing slashes.
|
||||
// It returns the case-corrected path and a bool indicating whether the lookup
|
||||
// was successful.
|
||||
func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
|
||||
return n.findCaseInsensitivePathRec(
|
||||
path,
|
||||
make([]byte, 0, len(path)+1), // preallocate enough memory for new path
|
||||
[4]byte{}, // empty rune buffer
|
||||
fixTrailingSlash,
|
||||
)
|
||||
}
|
||||
|
||||
// shift bytes in array by n bytes left
|
||||
func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
|
||||
switch n {
|
||||
case 0:
|
||||
return rb
|
||||
case 1:
|
||||
return [4]byte{rb[1], rb[2], rb[3], 0}
|
||||
case 2:
|
||||
return [4]byte{rb[2], rb[3]}
|
||||
case 3:
|
||||
return [4]byte{rb[3]}
|
||||
default:
|
||||
return [4]byte{}
|
||||
}
|
||||
}
|
||||
|
||||
// recursive case-insensitive lookup function used by n.findCaseInsensitivePath
|
||||
func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) {
|
||||
npLen := len(n.path)
|
||||
|
||||
walk: // outer loop for walking the tree
|
||||
for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
|
||||
// add common prefix to result
|
||||
|
||||
oldPath := path
|
||||
path = path[npLen:]
|
||||
ciPath = append(ciPath, n.path...)
|
||||
|
||||
if len(path) > 0 {
|
||||
// If this node does not have a wildcard (param or catchAll) child,
|
||||
// we can just look up the next child node and continue to walk down
|
||||
// the tree
|
||||
if !n.wildChild {
|
||||
// skip rune bytes already processed
|
||||
rb = shiftNRuneBytes(rb, npLen)
|
||||
|
||||
if rb[0] != 0 {
|
||||
// old rune not finished
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == rb[0] {
|
||||
// continue with child node
|
||||
n = n.children[i]
|
||||
npLen = len(n.path)
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// process a new rune
|
||||
var rv rune
|
||||
|
||||
// find rune start
|
||||
// runes are up to 4 byte long,
|
||||
// -4 would definitely be another rune
|
||||
var off int
|
||||
for max := min(npLen, 3); off < max; off++ {
|
||||
if i := npLen - off; utf8.RuneStart(oldPath[i]) {
|
||||
// read rune from cached path
|
||||
rv, _ = utf8.DecodeRuneInString(oldPath[i:])
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// calculate lowercase bytes of current rune
|
||||
lo := unicode.ToLower(rv)
|
||||
utf8.EncodeRune(rb[:], lo)
|
||||
|
||||
// skip already processed bytes
|
||||
rb = shiftNRuneBytes(rb, off)
|
||||
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
// lowercase matches
|
||||
if n.indices[i] == rb[0] {
|
||||
// must use a recursive approach since both the
|
||||
// uppercase byte and the lowercase byte might exist
|
||||
// as an index
|
||||
if out, found := n.children[i].findCaseInsensitivePathRec(
|
||||
path, ciPath, rb, fixTrailingSlash,
|
||||
); found {
|
||||
return out, true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// if we found no match, the same for the uppercase rune,
|
||||
// if it differs
|
||||
if up := unicode.ToUpper(rv); up != lo {
|
||||
utf8.EncodeRune(rb[:], up)
|
||||
rb = shiftNRuneBytes(rb, off)
|
||||
|
||||
for i, c := 0, rb[0]; i < len(n.indices); i++ {
|
||||
// uppercase matches
|
||||
if n.indices[i] == c {
|
||||
// continue with child node
|
||||
n = n.children[i]
|
||||
npLen = len(n.path)
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found. We can recommend to redirect to the same URL
|
||||
// without a trailing slash if a leaf exists for that path
|
||||
return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil)
|
||||
}
|
||||
|
||||
n = n.children[0]
|
||||
switch n.nType {
|
||||
case param:
|
||||
// find param end (either '/' or path end)
|
||||
k := 0
|
||||
for k < len(path) && path[k] != '/' {
|
||||
k++
|
||||
}
|
||||
|
||||
// add param value to case insensitive path
|
||||
ciPath = append(ciPath, path[:k]...)
|
||||
|
||||
// we need to go deeper!
|
||||
if k < len(path) {
|
||||
if len(n.children) > 0 {
|
||||
// continue with child node
|
||||
n = n.children[0]
|
||||
npLen = len(n.path)
|
||||
path = path[k:]
|
||||
continue
|
||||
}
|
||||
|
||||
// ... but we can't
|
||||
if fixTrailingSlash && len(path) == k+1 {
|
||||
return ciPath, true
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
|
||||
if n.handle != nil {
|
||||
return ciPath, true
|
||||
} else if fixTrailingSlash && len(n.children) == 1 {
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists
|
||||
n = n.children[0]
|
||||
if n.path == "/" && n.handle != nil {
|
||||
return append(ciPath, '/'), true
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
|
||||
case catchAll:
|
||||
return append(ciPath, path...), true
|
||||
|
||||
default:
|
||||
panic("invalid node type")
|
||||
}
|
||||
} else {
|
||||
// We should have reached the node containing the handle.
|
||||
// Check if this node has a handle registered.
|
||||
if n.handle != nil {
|
||||
return ciPath, true
|
||||
}
|
||||
|
||||
// No handle found.
|
||||
// Try to fix the path by adding a trailing slash
|
||||
if fixTrailingSlash {
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == '/' {
|
||||
n = n.children[i]
|
||||
if (len(n.path) == 1 && n.handle != nil) ||
|
||||
(n.nType == catchAll && n.children[0].handle != nil) {
|
||||
return append(ciPath, '/'), true
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found.
|
||||
// Try to fix the path by adding / removing a trailing slash
|
||||
if fixTrailingSlash {
|
||||
if path == "/" {
|
||||
return ciPath, true
|
||||
}
|
||||
if len(path)+1 == npLen && n.path[len(path)] == '/' &&
|
||||
strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handle != nil {
|
||||
return append(ciPath, n.path...), true
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
# Package `grpc`
|
||||
|
||||
Пакет `grpc` предоставляет инструменты для создания и управления gRPC-серверами, включая обработку аутентификации,
|
||||
маршрутизацию запросов и интеграцию с метаданными.
|
||||
Поддерживает гибкую настройку обработчиков, безопасное обновление сервисов и работу с заголовками.
|
||||
|
||||
## Types
|
||||
|
||||
### Server
|
||||
|
||||
gRPC-сервер с поддержкой динамического обновления обработчиков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `DefaultServer(restOptions ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать gRPC-сервер с настройками по умолчанию (максимальный размер сообщения 64 МБ).
|
||||
|
||||
#### `NewServer(opts ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать кастомный сервер с указанными опциями gRPC.
|
||||
|
||||
#### `(s *Server) Upgrade(service isp.BackendServiceServer)`
|
||||
|
||||
Атомарно обновить обработчик сервиса без остановки сервера.
|
||||
|
||||
#### `(s *Server) ListenAndServe(address string) error`
|
||||
|
||||
Запустить сервер на указанном адресе.
|
||||
|
||||
#### `(s *Server) Serve(listener net.Listener) error`
|
||||
|
||||
Запустить сервер на существующем listener.
|
||||
|
||||
#### `(s *Server) Shutdown()`
|
||||
|
||||
Остановить сервер
|
||||
|
||||
### Mux
|
||||
|
||||
Мультиплексор для маршрутизации gRPC-запросов. Регистрирует обработчики по имени эндпоинта.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMux() *Mux`
|
||||
|
||||
Создать новый мультиплексор.
|
||||
|
||||
#### `(m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux`
|
||||
|
||||
Зарегистрировать обработчик для указанного эндпоинта.
|
||||
|
||||
#### `(m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Обрабатывает входящий запрос, определяя эндпоинт через заголовок `ProxyMethodNameHeader`.
|
||||
|
||||
### AuthData
|
||||
|
||||
Структура для работы с метаданными аутентификации в gRPC-запросах.
|
||||
Оборачивает `metadata.MD` и предоставляет методы для извлечения идентификаторов из заголовков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(i AuthData) SystemId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-system-identity`.
|
||||
|
||||
#### `(i AuthData) DomainId() (int, error)`
|
||||
|
||||
Получить идентификатор домена из заголовка `x-domain-identity`.
|
||||
|
||||
#### `(i AuthData) ServiceId() (int, error)`
|
||||
|
||||
Получить идентификатор сервиса из заголовка `x-service-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-application-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationName() (int, error)`
|
||||
|
||||
Получить название системы из заголовка `x-application-name`.
|
||||
|
||||
#### `(i AuthData) UserId() (int, error)`
|
||||
|
||||
Получить идентификатор пользователя из заголовка `x-user-identity`.
|
||||
|
||||
#### `(i AuthData) DeviceId() (int, error)`
|
||||
|
||||
Получить идентификатор устройства из заголовка `x-device-identity`.
|
||||
|
||||
#### `(i AuthData) UserToken() (string, error)`
|
||||
|
||||
Получить токен пользователя из заголовка `x-user-token`.
|
||||
|
||||
#### `(i AuthData) DeviceToken() (string, error)`
|
||||
|
||||
Получить токен устройства из заголовка `x-device-token`.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `StringFromMd(key string, md metadata.MD) (string, error)`
|
||||
|
||||
Извлекает строковое значение из метаданных по ключу.
|
||||
|
||||
#### `IntFromMd(key string, md metadata.MD) (int, error)`
|
||||
|
||||
Извлекает целочисленное значение из метаданных по ключу.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mux := grpc.NewMux()
|
||||
mux.Handle("/get_users", func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
/* put here business logic */
|
||||
return new(isp.Message), nil
|
||||
})
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err := srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
// Package apierrors provides structured error handling for gRPC services.
|
||||
// It defines custom error types with business error codes, gRPC status codes,
|
||||
// and structured details for comprehensive error reporting.
|
||||
//
|
||||
// Errors can be converted to gRPC status errors with JSON-encoded details,
|
||||
// enabling rich error information to be transmitted across service boundaries.
|
||||
package apierrors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ErrCodeInternal is the default error code for internal service errors.
|
||||
ErrCodeInternal = 900
|
||||
)
|
||||
|
||||
// Error represents a structured error with business and gRPC status codes.
|
||||
// Includes optional details for field-specific errors and a configurable log level.
|
||||
// Implements the GrpcError interface for conversion to gRPC status errors.
|
||||
//
|
||||
// Fields:
|
||||
// - ErrorCode: Business-level error code (e.g., 400 for bad request)
|
||||
// - ErrorMessage: Human-readable error message
|
||||
// - Details: Optional map of field-specific error details
|
||||
// - grpcStatusCode: gRPC status code (e.g., codes.InvalidArgument)
|
||||
// - cause: Underlying error cause
|
||||
// - level: Log level for error logging
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMessage string
|
||||
Details map[string]any `json:",omitempty"`
|
||||
|
||||
grpcStatusCode codes.Code
|
||||
cause error
|
||||
level log.Level
|
||||
}
|
||||
|
||||
// NewInternalServiceError creates a new internal service error.
|
||||
// Uses gRPC status code Internal and business error code 900.
|
||||
// Sets log level to Error.
|
||||
func NewInternalServiceError(err error) Error {
|
||||
return New(codes.Internal, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
|
||||
}
|
||||
|
||||
// NewBusinessError creates a new business validation error.
|
||||
// Uses gRPC status code InvalidArgument and the specified error code.
|
||||
// Sets log level to Warn.
|
||||
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
|
||||
return New(codes.InvalidArgument, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
// New creates a new Error with the specified parameters.
|
||||
// Sets default log level to Error.
|
||||
func New(
|
||||
grpcStatusCode codes.Code,
|
||||
errorCode int,
|
||||
errorMessage string,
|
||||
err error,
|
||||
) Error {
|
||||
return Error{
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
grpcStatusCode: grpcStatusCode,
|
||||
cause: err,
|
||||
level: log.ErrorLevel,
|
||||
}
|
||||
}
|
||||
|
||||
// Error returns a string representation of the error.
|
||||
// Includes error code, message, and underlying cause.
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
|
||||
}
|
||||
|
||||
// GrpcStatusError converts the Error to a gRPC status error.
|
||||
// Serializes the error to JSON and attaches it as gRPC status details.
|
||||
// Returns an error if JSON marshaling or status creation fails.
|
||||
func (e Error) GrpcStatusError() error {
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
|
||||
msg := &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}
|
||||
s, err := status.New(e.grpcStatusCode, e.ErrorMessage).WithDetails(msg)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "set status details")
|
||||
}
|
||||
return s.Err()
|
||||
}
|
||||
|
||||
// WithDetails sets the error details map.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithDetails(details map[string]any) Error {
|
||||
e.Details = details
|
||||
return e
|
||||
}
|
||||
|
||||
// WithLogLevel sets the log level for this error.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithLogLevel(level log.Level) Error {
|
||||
e.level = level
|
||||
return e
|
||||
}
|
||||
|
||||
// LogLevel returns the log level for this error.
|
||||
func (e Error) LogLevel() log.Level {
|
||||
return e.level
|
||||
}
|
||||
|
||||
// FromError extracts an Error from a gRPC status error.
|
||||
// Returns nil if the error is not a gRPC status error or if the details cannot be parsed.
|
||||
// Useful for checking if an error originated from a remote service.
|
||||
func FromError(err error) *Error {
|
||||
s, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, detail := range s.Details() {
|
||||
typedDetail, ok := detail.(*isp.Message)
|
||||
if ok {
|
||||
errData := Error{}
|
||||
err := json.Unmarshal(typedDetail.GetBytesBody(), &errData)
|
||||
// not an error
|
||||
if err != nil {
|
||||
return nil // nolint:nilerr
|
||||
}
|
||||
if errData.ErrorCode == 0 {
|
||||
return nil
|
||||
}
|
||||
return &errData
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// ApplicationIdHeader is the metadata key for application identity.
|
||||
ApplicationIdHeader = "x-application-identity"
|
||||
// ApplicationNameHeader is the metadata key for application name.
|
||||
ApplicationNameHeader = "x-application-name"
|
||||
// UserIdHeader is the metadata key for user identity.
|
||||
UserIdHeader = "x-user-identity"
|
||||
// DeviceIdHeader is the metadata key for device identity.
|
||||
DeviceIdHeader = "x-device-identity"
|
||||
// ServiceIdHeader is the metadata key for service identity.
|
||||
ServiceIdHeader = "x-service-identity"
|
||||
// DomainIdHeader is the metadata key for domain identity.
|
||||
DomainIdHeader = "x-domain-identity"
|
||||
// SystemIdHeader is the metadata key for system identity.
|
||||
SystemIdHeader = "x-system-identity"
|
||||
// UserTokenHeader is the metadata key for user token.
|
||||
UserTokenHeader = "x-user-token"
|
||||
// DeviceTokenHeader is the metadata key for device token.
|
||||
DeviceTokenHeader = "x-device-token"
|
||||
)
|
||||
|
||||
// AuthData wraps metadata.MD to provide structured access to authentication
|
||||
// and authorization information from gRPC request metadata.
|
||||
// All methods return an error if the key is not found or cannot be parsed.
|
||||
type AuthData metadata.MD
|
||||
|
||||
// SystemId extracts the system identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) SystemId() (int, error) {
|
||||
return IntFromMd(SystemIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DomainId extracts the domain identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DomainId() (int, error) {
|
||||
return IntFromMd(DomainIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ServiceId extracts the service identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ServiceId() (int, error) {
|
||||
return IntFromMd(ServiceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationId extracts the application identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ApplicationId() (int, error) {
|
||||
return IntFromMd(ApplicationIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationName extracts the application name from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) ApplicationName() (string, error) {
|
||||
return StringFromMd(ApplicationNameHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserId extracts the user identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) UserId() (int, error) {
|
||||
return IntFromMd(UserIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceId extracts the device identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DeviceId() (int, error) {
|
||||
return IntFromMd(DeviceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserToken extracts the user token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) UserToken() (string, error) {
|
||||
return StringFromMd(UserTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceToken extracts the device token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) DeviceToken() (string, error) {
|
||||
return StringFromMd(DeviceTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// StringFromMd extracts a string value from metadata by key.
|
||||
// Returns an error if metadata is nil or the key is not found.
|
||||
func StringFromMd(key string, md metadata.MD) (string, error) {
|
||||
if md == nil {
|
||||
return "", errors.New("metadata is nil")
|
||||
}
|
||||
values := md[key]
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in metadata", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromMd extracts an integer value from metadata by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromMd(key string, md metadata.MD) (int, error) {
|
||||
value, err := StringFromMd(key, md)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
# Package `client`
|
||||
|
||||
Пакет `client` предоставляет гибкий gRPC-клиент с поддержкой балансировки нагрузки, middleware для логирования, метрик,
|
||||
трассировки и динамическим обновлением списка хостов.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура клиента для взаимодействия с gRPC-серверами. Поддерживает балансировку нагрузки, цепочки middleware и
|
||||
динамическое обновление списка хостов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(initialHosts []string, opts ...Option) (*Client, error)`
|
||||
|
||||
Создать новый клиент с указанными начальными хостами и опциями:
|
||||
|
||||
- `WithMiddlewares(middlewares ...request.Middleware) Option` – добавить middleware в цепочку обработки запроса.
|
||||
- `WithDialOptions(dialOptions ...grpc.DialOption) Option` – опция для передачи параметров подключения gRPC (например,
|
||||
TLS, таймауты)
|
||||
- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию `zstd`
|
||||
- `WithEncodeThreshold(threshold int) Option` – переопределяет значение выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest), по умолчанию 128 КБ (параметр в байтах).
|
||||
- `WithEncodeRequest(encode bool) Option` – переопределить флаг кодирования запроса. Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `x-content-encoding` со значением типа codec и тело запроса будет закодировано, по умолчанию false.
|
||||
- `WithAcceptEncodedResponse(accept bool) Option` – переопределить флаг флаг приёма закодированных ответов. Если включен, то в заголовки запроса будет добавлен `x-accept-encoding` со значением типа codec + identity (пример `zstd, identity`), по умолчанию true.
|
||||
|
||||
#### `(cli *Client) Invoke(endpoint string) *request.Builder`
|
||||
|
||||
Инициирует запрос к указанному эндпоинту. Возвращает билдер для выполнения запроса.
|
||||
|
||||
#### `(cli *Client) Upgrade(hosts []string)`
|
||||
|
||||
Атомарно обновить список хостов.
|
||||
|
||||
#### `(cli *Client) Close() error`
|
||||
|
||||
Закрыть соединение с сервером.
|
||||
|
||||
#### `(cli *Client) BackendClient() isp.BackendServiceClient`
|
||||
|
||||
Получить низкоуровневый клиент для прямого взаимодействия с gRPC-сервисом.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
users := make([]user, 0)
|
||||
err = cli.Invoke("/get_users").
|
||||
JsonResponseBody(&users).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
/* handle each user */
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
-210
@@ -1,210 +0,0 @@
|
||||
// Package client provides a gRPC client implementation with built-in load balancing,
|
||||
// middleware support, and observability features.
|
||||
//
|
||||
// The client supports dynamic host updates for service discovery and integrates with
|
||||
// the ISP kit framework's logging, metrics, and tracing systems.
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
grpc2 "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/resolver"
|
||||
"google.golang.org/grpc/resolver/manual"
|
||||
)
|
||||
|
||||
const (
|
||||
// resolverScheme defines the custom resolver scheme for host discovery.
|
||||
resolverScheme = "isp"
|
||||
// resolverUrl is the target URL for the manual resolver.
|
||||
resolverUrl = resolverScheme + ":///"
|
||||
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
type Codec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// Client is a gRPC client with support for middleware, load balancing, and dynamic host updates.
|
||||
// It provides a fluent API for building requests and automatically handles connection management.
|
||||
// Client is safe for concurrent use by multiple goroutines.
|
||||
type Client struct {
|
||||
middlewares []request.Middleware
|
||||
dialOptions []grpc.DialOption
|
||||
|
||||
roundTripper request.RoundTripper
|
||||
hostsResolver *manual.Resolver
|
||||
grpcCli *grpc.ClientConn
|
||||
backendCli isp.BackendServiceClient
|
||||
|
||||
currentHosts atomic.Value
|
||||
|
||||
codec Codec
|
||||
encodeThreshold int
|
||||
acceptEncodedResponse bool
|
||||
encodeRequest bool
|
||||
}
|
||||
|
||||
// New creates a new Client with the specified initial hosts and options.
|
||||
// Returns an error if the gRPC client cannot be initialized.
|
||||
// The client automatically connects to the provided hosts and applies all configured middleware.
|
||||
func New(initialHosts []string, opts ...Option) (*Client, error) {
|
||||
cli := &Client{
|
||||
codec: codec.Default,
|
||||
acceptEncodedResponse: true,
|
||||
encodeRequest: false,
|
||||
encodeThreshold: defaultEncodeThreshold,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cli)
|
||||
}
|
||||
|
||||
hostsResolver := manual.NewBuilderWithScheme(resolverScheme)
|
||||
hostsResolver.InitialState(resolver.State{
|
||||
Addresses: toAddresses(initialHosts),
|
||||
})
|
||||
dialOptions := cli.dialOptions
|
||||
dialOptions = append(
|
||||
dialOptions,
|
||||
grpc.WithResolvers(hostsResolver),
|
||||
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
|
||||
)
|
||||
|
||||
grpcCli, err := grpc.NewClient(resolverUrl, dialOptions...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new grpc client")
|
||||
}
|
||||
grpcCli.Connect()
|
||||
backendCli := isp.NewBackendServiceClient(grpcCli)
|
||||
|
||||
cli.currentHosts = atomic.Value{}
|
||||
cli.currentHosts.Store(initialHosts)
|
||||
cli.hostsResolver = hostsResolver
|
||||
cli.backendCli = backendCli
|
||||
cli.grpcCli = grpcCli
|
||||
|
||||
roundTripper := cli.do
|
||||
for _, v := range slices.Backward(cli.middlewares) {
|
||||
roundTripper = v(roundTripper)
|
||||
}
|
||||
cli.roundTripper = roundTripper
|
||||
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
// Invoke creates a request builder for the specified endpoint.
|
||||
// The builder provides a fluent API for configuring and executing the request.
|
||||
func (cli *Client) Invoke(endpoint string) *request.Builder {
|
||||
return request.NewBuilder(
|
||||
cli.roundTripper,
|
||||
endpoint,
|
||||
request.EncodeSettings{
|
||||
EncodeRequest: cli.encodeRequest,
|
||||
EncodeThreshold: cli.encodeThreshold,
|
||||
AcceptEncodedResponse: cli.acceptEncodedResponse,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Upgrade updates the list of backend hosts for load balancing.
|
||||
// This enables dynamic service discovery without restarting the client.
|
||||
// Thread-safe for concurrent use.
|
||||
func (cli *Client) Upgrade(hosts []string) {
|
||||
cli.currentHosts.Store(hosts)
|
||||
cli.hostsResolver.UpdateState(resolver.State{
|
||||
Addresses: toAddresses(hosts),
|
||||
})
|
||||
}
|
||||
|
||||
// Close closes the gRPC client connection.
|
||||
// Should be called when the client is no longer needed.
|
||||
func (cli *Client) Close() error {
|
||||
return cli.grpcCli.Close()
|
||||
}
|
||||
|
||||
// BackendClient returns the underlying gRPC BackendServiceClient.
|
||||
// Useful for direct gRPC calls bypassing the client abstraction.
|
||||
func (cli *Client) BackendClient() isp.BackendServiceClient {
|
||||
return cli.backendCli
|
||||
}
|
||||
|
||||
// do executes the actual gRPC request through the middleware chain.
|
||||
// Returns an error if the client is not properly initialized or the request fails.
|
||||
func (cli *Client) do(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
currentHosts := cli.currentHosts.Load().([]string) // nolint:forcetypeassert
|
||||
if len(currentHosts) == 0 {
|
||||
return nil, errors.New("grpc client: client is not initialized properly: empty hosts array")
|
||||
}
|
||||
|
||||
encodeSettings := builder.EncodeSettings
|
||||
if encodeSettings.AcceptEncodedResponse {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.AcceptEncodingHeader,
|
||||
strings.Join([]string{cli.codec.Type(), "identity"}, ", "),
|
||||
)
|
||||
}
|
||||
|
||||
requestBody := message.GetBytesBody()
|
||||
if encodeSettings.EncodeRequest && len(requestBody) > encodeSettings.EncodeThreshold {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.ContentEncodingHeader,
|
||||
cli.codec.Type(),
|
||||
)
|
||||
requestBody, err := cli.codec.EncodeBytes(requestBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message.Body = &isp.Message_BytesBody{
|
||||
BytesBody: requestBody,
|
||||
}
|
||||
}
|
||||
|
||||
var header metadata.MD
|
||||
resp, err := cli.backendCli.Request(
|
||||
ctx,
|
||||
message,
|
||||
grpc.Header(&header),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc2.StringFromMd(grpc2.ContentEncodingHeader, header)
|
||||
if contentEncoding != cli.codec.Type() {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
decoded, err := cli.codec.DecodeBytes(resp.GetBytesBody())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// toAddresses converts a slice of host strings to gRPC resolver addresses.
|
||||
func toAddresses(hosts []string) []resolver.Address {
|
||||
addresses := make([]resolver.Address, len(hosts))
|
||||
for i, host := range hosts {
|
||||
addresses[i] = resolver.Address{
|
||||
Addr: host,
|
||||
}
|
||||
}
|
||||
return addresses
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
ispgrpc "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// Default creates a Client with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, and distributed tracing.
|
||||
// Uses insecure transport by default (suitable for development and testing).
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
// Returns an error if the client cannot be initialized.
|
||||
func Default(restMiddlewares ...request.Middleware) (*Client, error) {
|
||||
middlewares := append(
|
||||
[]request.Middleware{
|
||||
RequestId(),
|
||||
Metrics(grpc_metrics.NewClientStorage(metrics.DefaultRegistry)),
|
||||
client_tracing.NewConfig().Middleware(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return New(
|
||||
nil,
|
||||
WithDialOptions(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.WaitForReady(true),
|
||||
grpc.MaxCallSendMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
grpc.MaxCallRecvMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
),
|
||||
),
|
||||
WithMiddlewares(middlewares...),
|
||||
)
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// logConfig holds logging configuration for client middleware.
|
||||
type logConfig struct {
|
||||
logRequestBody bool
|
||||
logResponseBody bool
|
||||
combinedLog bool
|
||||
}
|
||||
|
||||
// RequestId is a middleware that propagates request IDs across service boundaries.
|
||||
// If no request ID is present in the context, it generates a new one.
|
||||
// The request ID is added to outgoing metadata for tracing purposes.
|
||||
func RequestId() request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, requestid.Header, requestId)
|
||||
return next(ctx, builder, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log creates a middleware that logs gRPC client requests and responses.
|
||||
// When logBody is true, request and response bodies are included in the logs.
|
||||
// Logs at Debug level for requests and responses.
|
||||
func Log(logger log.Logger, logBody bool) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: logBody,
|
||||
logResponseBody: logBody,
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// LogWithOptions creates a middleware that logs gRPC client requests and responses with custom options.
|
||||
// Provides fine-grained control over what is logged (request body, response body, combined logs).
|
||||
func LogWithOptions(logger log.Logger, opts ...LogOption) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: false,
|
||||
logResponseBody: false,
|
||||
combinedLog: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
if cfg.combinedLog {
|
||||
return logCombinedMiddleware(logger, cfg)
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// logMiddleware implements request/response logging with separate log entries.
|
||||
func logMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
requestFields = append(requestFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: request", requestFields...)
|
||||
|
||||
var responseFields []log.Field
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
if err != nil {
|
||||
responseFields = append(responseFields,
|
||||
log.Any("error", err),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
logger.Debug(ctx, "grpc client: response with error", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
responseFields = append(responseFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
if cfg.logResponseBody {
|
||||
responseFields = append(responseFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "grpc client: response", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// logCombinedMiddleware implements logging with a single combined log entry.
|
||||
func logCombinedMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
logFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
logFields = append(logFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
|
||||
logFields = append(logFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logFields = append(logFields, log.Any("error", err))
|
||||
logger.Debug(ctx, "grpc client: log with error", logFields...)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if cfg.logResponseBody {
|
||||
logFields = append(logFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: log", logFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MetricStorage defines the interface for metric storage implementations.
|
||||
// Used by the Metrics middleware to collect timing information.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given endpoint.
|
||||
ObserveDuration(endpoint string, duration time.Duration)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects timing metrics for gRPC client requests.
|
||||
// The storage implementation receives the endpoint name and request duration.
|
||||
func Metrics(storage MetricStorage) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
start := time.Now()
|
||||
response, err := next(ctx, builder, message)
|
||||
storage.ObserveDuration(builder.Endpoint, time.Since(start))
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Option configures a Client using the functional options pattern.
|
||||
type Option func(cli *Client)
|
||||
|
||||
// WithMiddlewares adds one or more request middleware to the client.
|
||||
// Middleware are executed in the order they are provided.
|
||||
func WithMiddlewares(middlewares ...request.Middleware) Option {
|
||||
return func(cli *Client) {
|
||||
cli.middlewares = append(cli.middlewares, middlewares...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithDialOptions sets custom gRPC dial options for the client.
|
||||
// Note: This replaces any previously set dial options.
|
||||
func WithDialOptions(dialOptions ...grpc.DialOption) Option {
|
||||
return func(cli *Client) {
|
||||
cli.dialOptions = dialOptions
|
||||
}
|
||||
}
|
||||
|
||||
// WithAcceptEncodedResponse sets acceptEncodedResponse flag.
|
||||
func WithAcceptEncodedResponse(accept bool) Option {
|
||||
return func(c *Client) {
|
||||
c.acceptEncodedResponse = accept
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeRequest sets encodeRequest flag.
|
||||
func WithEncodeRequest(encode bool) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeRequest = encode
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeThreshold sets the request encoding threshold in bytes.
|
||||
func WithEncodeThreshold(thresholdBytes int) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeThreshold = thresholdBytes
|
||||
}
|
||||
}
|
||||
|
||||
// WithCodec sets codec.
|
||||
func WithCodec(codec Codec) Option {
|
||||
return func(c *Client) {
|
||||
c.codec = codec
|
||||
}
|
||||
}
|
||||
|
||||
// LogOption configures logging behavior for request middleware.
|
||||
type LogOption func(cfg *logConfig)
|
||||
|
||||
// WithLogBody enables logging of both request and response bodies.
|
||||
func WithLogBody(logBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logBody
|
||||
cfg.logRequestBody = logBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogResponseBody enables or disables logging of response bodies.
|
||||
func WithLogResponseBody(logResponseBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logResponseBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogRequestBody enables or disables logging of request bodies.
|
||||
func WithLogRequestBody(logRequestBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logRequestBody = logRequestBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithCombinedLog enables a single combined log entry for request and response.
|
||||
// When disabled, requests and responses are logged separately.
|
||||
func WithCombinedLog(enable bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.combinedLog = enable
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# Package `request`
|
||||
|
||||
Пакет `request` предоставляет билдер для построения gRPC-запросов с поддержкой JSON-сериализации, таймаутов, метаданных
|
||||
и цепочек обработки через middleware. Интегрируется с клиентом из пакета [`client`](../client.go).
|
||||
|
||||
## Types
|
||||
|
||||
### Builder
|
||||
|
||||
Структура для пошагового конструирования gRPC-запроса. Обрабатывает сериализацию/десериализацию JSON, управление
|
||||
контекстом и метаданными.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewBuilder(roundTripper RoundTripper, endpoint string) *Builder`
|
||||
|
||||
Создать новый билдер для указанного эндпоинта.
|
||||
|
||||
#### `(req *Builder) ApplicationId(appId int) *Builder`
|
||||
|
||||
Установить идентификатор системы в заголовок `x-application-identity`.
|
||||
|
||||
#### `(req *Builder) JsonRequestBody(reqBody any) *Builder`
|
||||
|
||||
Задать тело запроса в формате JSON. Объект будет сериализован автоматически при помощи функций из пакета [
|
||||
`json`](../../json) (маршалинг без тэгов в camelCase).
|
||||
|
||||
#### `(req *Builder) JsonResponseBody(respPtr any) *Builder`
|
||||
|
||||
Задать указатель для десериализации тела ответа из JSON.
|
||||
|
||||
#### `(req *Builder) Timeout(timeout time.Duration) *Builder`
|
||||
|
||||
Установить тайм-аут для запроса. По умолчанию: 15 секунд.
|
||||
|
||||
#### `(req *Builder) AppendMetadata(k string, v ...string) *Builder`
|
||||
|
||||
Добавить кастомные метаданные в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг кодирования запроса.
|
||||
Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `content-encoding` со значением типа codec и тело запроса будет закодировано.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder`
|
||||
|
||||
Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).
|
||||
|
||||
#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder`
|
||||
|
||||
Установить флаг приёма закодированных ответов.
|
||||
Если включен, то в заголовки запроса будет добавлен `accept-encoding` со значением типа codec + identity (пример `zstd, identity`).
|
||||
|
||||
#### `(req *Builder) Do(ctx context.Context) error`
|
||||
|
||||
Выполнить запрос. Автоматически:
|
||||
|
||||
1. Сериализует тело запроса в JSON
|
||||
2. Добавляет системные заголовки (`x-application-identity`, `proxy_method_name`)
|
||||
3. Обрабатывает цепочку middleware
|
||||
4. Десериализует ответ (если задан `responsePtr`)
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
u := new(user)
|
||||
err = cli.Invoke("/get_user").
|
||||
ApplicationId(88).
|
||||
JsonRequestBody(getUserRequest{Id: "some-user-id"}).
|
||||
JsonResponseBody(u).
|
||||
Timeout(5 * time.Second).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
log.Printf("username: %s\n", u.Name)
|
||||
}
|
||||
|
||||
```
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
// Package request provides a fluent builder for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling/unmarshaling, metadata management, and timeout configuration.
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTimeout is the default request timeout when none is specified.
|
||||
defaultTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type EncodeSettings struct {
|
||||
EncodeRequest bool
|
||||
EncodeThreshold int
|
||||
AcceptEncodedResponse bool
|
||||
}
|
||||
|
||||
// Builder provides a fluent API for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling, metadata management, and timeout configuration.
|
||||
// Builder is not safe for concurrent use; create a new instance for each request.
|
||||
type Builder struct {
|
||||
Endpoint string
|
||||
MD metadata.MD
|
||||
EncodeSettings EncodeSettings
|
||||
|
||||
requestBody any
|
||||
responsePtr any
|
||||
applicationId int
|
||||
timeout time.Duration
|
||||
roundTripper RoundTripper
|
||||
}
|
||||
|
||||
// NewBuilder creates a new Builder for the specified endpoint.
|
||||
// Initializes with default timeout and empty metadata.
|
||||
func NewBuilder(
|
||||
roundTripper RoundTripper,
|
||||
endpoint string,
|
||||
encodeSettings EncodeSettings,
|
||||
) *Builder {
|
||||
return &Builder{
|
||||
Endpoint: endpoint,
|
||||
MD: metadata.New(make(map[string]string)),
|
||||
roundTripper: roundTripper,
|
||||
timeout: defaultTimeout,
|
||||
EncodeSettings: encodeSettings,
|
||||
}
|
||||
}
|
||||
|
||||
// ApplicationId sets the application identity header for the request.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) ApplicationId(appId int) *Builder {
|
||||
req.applicationId = appId
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonRequestBody sets the request body as a JSON-encodable value.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonRequestBody(reqBody any) *Builder {
|
||||
req.requestBody = reqBody
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonResponseBody sets the pointer to unmarshal the JSON response into.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonResponseBody(respPtr any) *Builder {
|
||||
req.responsePtr = respPtr
|
||||
return req
|
||||
}
|
||||
|
||||
// Timeout sets the request timeout duration.
|
||||
// A timeout of zero or negative disables the timeout.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) Timeout(timeout time.Duration) *Builder {
|
||||
req.timeout = timeout
|
||||
return req
|
||||
}
|
||||
|
||||
// AppendMetadata adds one or more values to the metadata key.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) AppendMetadata(k string, v ...string) *Builder {
|
||||
req.MD[k] = append(req.MD[k], v...)
|
||||
return req
|
||||
}
|
||||
|
||||
// EncodeRequest sets encoding for request body.
|
||||
// It affects content-encoding and request body serialization.
|
||||
func (b *Builder) EncodeRequest(encode bool) *Builder {
|
||||
b.EncodeSettings.EncodeRequest = encode
|
||||
return b
|
||||
}
|
||||
|
||||
// AcceptEncodedResponse enables transparent handling of encoded GRPC responses.
|
||||
//
|
||||
// When enabled, the client adds "accept-encoding" (e.g. zstd) to request headers,
|
||||
// allowing the server to return encoded payloads.
|
||||
func (b *Builder) AcceptEncodedResponse(accept bool) *Builder {
|
||||
b.EncodeSettings.AcceptEncodedResponse = accept
|
||||
return b
|
||||
}
|
||||
|
||||
// EncodeThreshold sets the request encoding threshold in bytes.
|
||||
func (b *Builder) EncodeThreshold(thresholdBytes int) *Builder {
|
||||
b.EncodeSettings.EncodeThreshold = thresholdBytes
|
||||
return b
|
||||
}
|
||||
|
||||
// Do executes the request and unmarshals the response if a response pointer was provided.
|
||||
// Returns an error if JSON marshaling, request execution, or response unmarshaling fails.
|
||||
// Automatically applies the configured timeout to the request context.
|
||||
func (req *Builder) Do(ctx context.Context) error {
|
||||
var (
|
||||
reqCtx = ctx
|
||||
cancel context.CancelFunc
|
||||
)
|
||||
if req.timeout > 0 {
|
||||
reqCtx, cancel = context.WithTimeout(ctx, req.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
req.MD.Set(grpc.ProxyMethodNameHeader, req.Endpoint)
|
||||
if req.applicationId != 0 {
|
||||
req.MD.Set(grpc.ApplicationIdHeader, strconv.Itoa(req.applicationId))
|
||||
}
|
||||
ctx = metadata.NewOutgoingContext(reqCtx, req.MD)
|
||||
|
||||
var body []byte
|
||||
var err error
|
||||
if req.requestBody != nil {
|
||||
body, err = json.Marshal(req.requestBody)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal to json request body")
|
||||
}
|
||||
}
|
||||
message := &isp.Message{Body: &isp.Message_BytesBody{BytesBody: body}}
|
||||
|
||||
resp, err := req.roundTripper(ctx, req, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.responsePtr != nil {
|
||||
err = json.Unmarshal(resp.GetBytesBody(), req.responsePtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal response body")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// RoundTripper defines the interface for executing gRPC requests.
|
||||
// Receives a context, request builder, and message; returns a response message and optional error.
|
||||
// Used as the base for middleware chains.
|
||||
type RoundTripper func(ctx context.Context, builder *Builder, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a RoundTripper to add cross-cutting concerns like logging,
|
||||
// metrics, authentication, or error handling.
|
||||
// Middleware functions are typically chained in reverse order of execution.
|
||||
type Middleware func(next RoundTripper) RoundTripper
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// HandlerFunc defines the signature for gRPC request handlers.
|
||||
// Receives a context and message, returns a response message and optional error.
|
||||
type HandlerFunc func(ctx context.Context, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a HandlerFunc to add cross-cutting concerns like logging,
|
||||
// metrics, authentication, or error handling.
|
||||
// Middleware functions are typically chained in reverse order of execution.
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package grpc
|
||||
|
||||
const (
|
||||
// AcceptEncodingHeader is the metadata key for accept encoding.
|
||||
AcceptEncodingHeader = "x-accept-encoding"
|
||||
|
||||
// ContentEncodingHeader is the metadata key for content encoding.
|
||||
ContentEncodingHeader = "x-content-encoding"
|
||||
)
|
||||
-268
@@ -1,268 +0,0 @@
|
||||
# Package `endpoint`
|
||||
|
||||
Пакет `endpoint` предоставляет инструменты для создания gRPC-обработчиков с автоматической сериализацией JSON,
|
||||
валидацией запросов, middleware-цепочками и интеграцией метрик/логирования. Реализует паттерн "Endpoint" для изоляции
|
||||
бизнес-логики от транспортного слоя.
|
||||
|
||||
## Types
|
||||
|
||||
### Wrapper
|
||||
|
||||
Основная структура для создания цепочек обработки запросов. Объединяет:
|
||||
|
||||
- Маппинг параметров
|
||||
- Middleware (логирование, метрики, восстановление после паник)
|
||||
- Сериализацию/валидацию JSON
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper) Wrapper`
|
||||
|
||||
Создает конфигурацию для обработчиков.
|
||||
Параметры:
|
||||
|
||||
- `paramMappers` – правила извлечения параметров из контекста/метаданных
|
||||
- `bodyExtractor` – десериализация и валидация тела запроса
|
||||
- `bodyMapper` – сериализация ответа
|
||||
|
||||
#### `(m Wrapper) Endpoint(f any) grpc.HandlerFunc`
|
||||
|
||||
Преобразует пользовательскую функцию в gRPC-обработчик.
|
||||
Функция `f` может содержать параметры:
|
||||
|
||||
- `context.Context`
|
||||
- `grpc.AuthData` (метаданные аутентификации)
|
||||
- Пользовательский тип (десериализуется из JSON-тела)
|
||||
|
||||
#### `(m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Добавляет middleware в цепочку обработки.
|
||||
|
||||
### Caller
|
||||
|
||||
Внутренняя структура для вызова пользовательских обработчиков. Автоматически:
|
||||
|
||||
- Извлекает параметры
|
||||
- Вызывает middleware
|
||||
- Обрабатывает ошибки
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`NewCaller(f any,bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)`
|
||||
|
||||
Создает экземпляр `Caller` для функции-обработчика.
|
||||
|
||||
#### `(h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
|
||||
|
||||
### JsonRequestExtractor
|
||||
|
||||
Реализация интерфейса `RequestBodyExtractor` для работы с JSON. Валидирует данные с помощью объекта, реализующего
|
||||
интерфейс `Validator`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`(j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)`
|
||||
|
||||
Десериализует и валидирует JSON-тело запроса через `Validator`.
|
||||
|
||||
### JsonResponseMapper
|
||||
|
||||
Сериализует ответ обработчика в JSON-тело gRPC-сообщения.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(j JsonResponseMapper) Map(result any) (*isp.Message, error)`
|
||||
|
||||
Конвертирует результат обработчика в gRPC-сообщение в формате JSON.
|
||||
|
||||
## Middlewares
|
||||
|
||||
### `MaxRequestBodySize`
|
||||
|
||||
Ограничивает размер тела запроса (по умолчанию 64 МБ).
|
||||
|
||||
### `RequestId`
|
||||
|
||||
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
|
||||
|
||||
### `DecodeRequest`
|
||||
Декодирует запрос при помощи переданного codec, если заголовок `x-content-encoding` совпадает с типом codec.
|
||||
|
||||
### `Metrics`
|
||||
|
||||
Собирает метрики: время выполнения, статусы, размеры тел.
|
||||
|
||||
### `Tracing`
|
||||
|
||||
Интеграция с трейсингом (OpenTelemetry).
|
||||
|
||||
### `EncodeResponse`
|
||||
|
||||
Кодирует ответ при помощи переданного codec, если заголовок `x-accept-encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
|
||||
|
||||
### `ErrorHandler`
|
||||
|
||||
Перехватывает и обрабатывает ошибки. Ошибки типа `GrpcError` возвращают структурированный ответ.
|
||||
Остальные ошибки логируются и возвращаются как Internal Server Error с gRPC-кодом 13.
|
||||
|
||||
### `Recovery`
|
||||
|
||||
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
#### `DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, декодирование запросов, кодировение ответов, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `DecodeRequest`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `EncodeResponse`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Codec usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultCodecWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// DefaultWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
|
||||
// DefaultCodecWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling, encode response, decode request,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
codec := codec.Default
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
DecodeRequest(codec),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
EncodeResponse(codec, defaultEncodeThreshold),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
const (
|
||||
// errCodeBadRequest is the error code for invalid request body errors.
|
||||
errCodeBadRequest = 400
|
||||
)
|
||||
|
||||
// Validator defines the interface for request validation.
|
||||
// Implementations should validate a value and return whether it's valid
|
||||
// along with field-specific error details.
|
||||
type Validator interface {
|
||||
// Validate checks if the value is valid.
|
||||
// Returns true if valid, false otherwise, along with a map of field names to error messages.
|
||||
Validate(value any) (bool, map[string]string)
|
||||
}
|
||||
|
||||
// JsonRequestExtractor extracts and validates JSON request bodies from gRPC messages.
|
||||
// Unmarshals the message body into the target type and validates it using the configured validator.
|
||||
type JsonRequestExtractor struct {
|
||||
Validator Validator
|
||||
}
|
||||
|
||||
// Extract unmarshals the message body as JSON and validates it.
|
||||
// Returns a reflect.Value of the created instance or an error if unmarshaling or validation fails.
|
||||
// Business validation errors are returned as apierrors.BusinessError with code 400.
|
||||
func (j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error) {
|
||||
instance := reflect.New(reqBodyType)
|
||||
err := json.Unmarshal(message.GetBytesBody(), instance.Interface())
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "unmarshal json request body")
|
||||
return reflect.Value{}, apierrors.NewBusinessError(errCodeBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
elem := instance.Elem()
|
||||
|
||||
ok, details := j.Validator.Validate(elem.Interface())
|
||||
if ok {
|
||||
return elem, nil
|
||||
}
|
||||
formattedDetails := formatDetails(details)
|
||||
return reflect.Value{}, apierrors.NewBusinessError(
|
||||
errCodeBadRequest,
|
||||
"invalid request body",
|
||||
errors.Errorf("validation errors: %v", formattedDetails),
|
||||
).WithDetails(formattedDetails)
|
||||
}
|
||||
|
||||
// formatDetails converts a map of field error messages to a format suitable for API responses.
|
||||
// Converts field names to lowercase (first character) for consistency.
|
||||
func formatDetails(details map[string]string) map[string]any {
|
||||
result := make(map[string]any, len(details))
|
||||
for k, v := range details {
|
||||
arr := []rune(k)
|
||||
arr[0] = unicode.ToLower(arr[0])
|
||||
result[string(arr)] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// JsonResponseMapper maps handler results to gRPC messages with JSON-encoded bodies.
|
||||
// Implements the ResponseBodyMapper interface.
|
||||
type JsonResponseMapper struct{}
|
||||
|
||||
// Map marshals the result to JSON and creates a gRPC message.
|
||||
// Returns an empty message body if result is nil.
|
||||
// Returns an error if JSON marshaling fails.
|
||||
func (j JsonResponseMapper) Map(result any) (*isp.Message, error) {
|
||||
if result == nil {
|
||||
return &isp.Message{Body: &isp.Message_BytesBody{}}, nil
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
return &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// MetricStorage defines the interface for collecting gRPC server metrics.
|
||||
// Implementations should record request durations, payload sizes, and response codes.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given method.
|
||||
ObserveDuration(method string, duration time.Duration)
|
||||
// ObserveRequestBodySize records the size of the request body.
|
||||
ObserveRequestBodySize(method string, size int)
|
||||
// ObserveResponseBodySize records the size of the response body.
|
||||
ObserveResponseBodySize(method string, size int)
|
||||
// CountStatusCode increments the counter for the given endpoint and status code.
|
||||
CountStatusCode(endpoint string, code codes.Code)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects metrics for gRPC server requests.
|
||||
// Records request duration, request/response body sizes, and response status codes.
|
||||
// The endpoint name is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
func Metrics(storage MetricStorage) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, err := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
storage.ObserveRequestBodySize(endpoint, len(message.GetBytesBody()))
|
||||
start := time.Now()
|
||||
response, err := next(ctx, message)
|
||||
storage.ObserveDuration(endpoint, time.Since(start))
|
||||
storage.CountStatusCode(endpoint, status.Code(err))
|
||||
if response != nil {
|
||||
storage.ObserveResponseBodySize(endpoint, len(response.GetBytesBody()))
|
||||
}
|
||||
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
-221
@@ -1,221 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/panic_recovery"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
grpc2 "google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
// Recovery creates a middleware that catches panics and converts them to errors.
|
||||
// Prevents gRPC server crashes from handler panics by recovering and returning the error.
|
||||
func Recovery() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (msg *isp.Message, err error) {
|
||||
defer panic_recovery.Recover(func(panicErr error) {
|
||||
err = panicErr
|
||||
})
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler creates a middleware that handles errors from downstream handlers.
|
||||
// Logs errors at appropriate levels, enriches them with Sentry context, and
|
||||
// converts custom GrpcError types to gRPC status errors.
|
||||
// Returns a generic "internal service error" for unknown error types to prevent
|
||||
// information leakage.
|
||||
func ErrorHandler(logger log.Logger) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
result, err := next(ctx, message)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
logFunc := logutil.LogLevelFuncForError(err, logger)
|
||||
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Request = sentryRequest(ctx)
|
||||
})
|
||||
logFunc(logContext, err)
|
||||
|
||||
var grpcErr GrpcError
|
||||
if errors.As(err, &grpcErr) {
|
||||
return result, grpcErr.GrpcStatusError()
|
||||
}
|
||||
|
||||
// deprecated approach
|
||||
_, ok := status.FromError(err)
|
||||
if ok {
|
||||
return result, err
|
||||
}
|
||||
|
||||
// hide error details to prevent potential security leaks
|
||||
return result, status.Error(codes.Internal, "internal service error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId creates a middleware that manages request IDs for tracing.
|
||||
// Extracts the request ID from incoming metadata, generates a new one if absent,
|
||||
// and injects it into the context for downstream use.
|
||||
func RequestId() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
values := md.Get(requestid.Header)
|
||||
requestId := ""
|
||||
if len(values) > 0 {
|
||||
requestId = values[0]
|
||||
}
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
ctx = requestid.ToContext(ctx, requestId)
|
||||
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
|
||||
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type DecodeCodec interface {
|
||||
Type() string
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// DecodeRequest returns middleware that transparently handles decoded requests.
|
||||
//
|
||||
// If x-content-encoding matches codec, request body is decoded.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see decoded data.
|
||||
func DecodeRequest(codec DecodeCodec) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc.StringFromMd(grpc.ContentEncodingHeader, md)
|
||||
reqBody := msg.GetBytesBody()
|
||||
if contentEncoding == codec.Type() {
|
||||
decoded, err := codec.DecodeBytes(reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
md.Delete(grpc.ContentEncodingHeader)
|
||||
ctx = metadata.NewIncomingContext(ctx, md)
|
||||
}
|
||||
|
||||
return next(ctx, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type EncodeCodec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// EncodeResponse returns middleware that transparently handles response encoding.
|
||||
//
|
||||
// If client supports x-accept-encoding and response body size > encodeThresholdBytes,
|
||||
// the response is encoded using codec.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see plain data.
|
||||
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
resp, err := next(ctx, msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check accept
|
||||
acceptEncoding, _ := grpc.StringFromMd(grpc.AcceptEncodingHeader, md)
|
||||
if !acceptsEncoding(acceptEncoding, codec.Type()) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
responseBody := resp.GetBytesBody()
|
||||
if len(responseBody) <= encodeThresholdBytes {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
err = grpc2.SetHeader(ctx, metadata.Pairs(
|
||||
grpc.ContentEncodingHeader, codec.Type(),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
encoded, err := codec.EncodeBytes(responseBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: encoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// acceptsEncoding split header and check contains encoding in it.
|
||||
func acceptsEncoding(header, encoding string) bool {
|
||||
for part := range strings.SplitSeq(header, ",") {
|
||||
if strings.TrimSpace(part) == encoding {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// sentryRequest creates a Sentry request object from the gRPC context.
|
||||
// Extracts endpoint and application ID from metadata for error tracking.
|
||||
func sentryRequest(ctx context.Context) *sentry.Request {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
applicationId, _ := grpc.StringFromMd(grpc.ApplicationIdHeader, md)
|
||||
return &sentry.Request{
|
||||
URL: endpoint,
|
||||
Method: "POST",
|
||||
Headers: map[string]string{
|
||||
grpc.ApplicationIdHeader: applicationId,
|
||||
},
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// ContextParam creates a ParamMapper for injecting context.Context into handlers.
|
||||
// The context is passed through from the incoming gRPC request context.
|
||||
func ContextParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "context.Context",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
return ctx, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// AuthDataParam creates a ParamMapper for injecting grpc.AuthData into handlers.
|
||||
// Extracts authentication and authorization information from the incoming request metadata.
|
||||
// Returns an error if metadata is not present in the context.
|
||||
func AuthDataParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "grpc.AuthData",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context") // nolint:err113
|
||||
}
|
||||
return grpc.AuthData(md), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
// Package endpoint provides a higher-level abstraction for building gRPC handlers.
|
||||
// It enables reflection-based function wrapping with automatic request/response
|
||||
// marshaling, parameter injection, and middleware support.
|
||||
//
|
||||
// The package integrates with the ISP kit framework's logging, metrics, and
|
||||
// validation systems for comprehensive observability and error handling.
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// GrpcError is an interface for errors that can be converted to gRPC status errors.
|
||||
// Implementations should return a gRPC status error with appropriate details.
|
||||
type GrpcError interface {
|
||||
GrpcStatusError() error
|
||||
}
|
||||
|
||||
// RequestBodyExtractor defines the interface for extracting request bodies from gRPC messages.
|
||||
// Implementations should unmarshal the message body into the target type and return a reflect.Value.
|
||||
type RequestBodyExtractor interface {
|
||||
// Extract unmarshals the message body into an instance of reqBodyType.
|
||||
// Returns the reflect.Value of the created instance and any unmarshaling or validation errors.
|
||||
Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)
|
||||
}
|
||||
|
||||
// ResponseBodyMapper defines the interface for mapping handler results to gRPC messages.
|
||||
// Implementations should marshal the result into a gRPC message body.
|
||||
type ResponseBodyMapper interface {
|
||||
// Map converts a handler result into a gRPC message.
|
||||
// Returns the message and any marshaling errors.
|
||||
Map(result any) (*isp.Message, error)
|
||||
}
|
||||
|
||||
// ParamBuilder defines a function that builds a parameter value from context and message.
|
||||
// Used by ParamMapper to inject dependencies like context, auth data, etc.
|
||||
type ParamBuilder func(ctx context.Context, message *isp.Message) (any, error)
|
||||
|
||||
// ParamMapper maps a parameter type string to a builder function.
|
||||
// Used to inject dependencies into handler functions automatically.
|
||||
type ParamMapper struct {
|
||||
// Type is the string representation of the parameter type.
|
||||
Type string
|
||||
// Builder is the function that creates the parameter value.
|
||||
Builder ParamBuilder
|
||||
}
|
||||
|
||||
// Wrapper is a high-level handler factory that wraps functions with middleware and
|
||||
// automatic request/response handling. It uses reflection to analyze function signatures
|
||||
// and inject dependencies like context and auth data.
|
||||
type Wrapper struct {
|
||||
ParamMappers map[string]ParamMapper
|
||||
BodyExtractor RequestBodyExtractor
|
||||
BodyMapper ResponseBodyMapper
|
||||
Middlewares []grpc.Middleware
|
||||
}
|
||||
|
||||
// NewWrapper creates a new Wrapper with the specified configuration.
|
||||
// Accepts variadic paramMappers, a body extractor, and a body mapper.
|
||||
func NewWrapper(
|
||||
paramMappers []ParamMapper,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
) Wrapper {
|
||||
mappers := make(map[string]ParamMapper)
|
||||
for _, mapper := range paramMappers {
|
||||
mappers[mapper.Type] = mapper
|
||||
}
|
||||
return Wrapper{
|
||||
ParamMappers: mappers,
|
||||
BodyExtractor: bodyExtractor,
|
||||
BodyMapper: bodyMapper,
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint wraps a function to create a gRPC HandlerFunc.
|
||||
// The function is analyzed via reflection to determine parameter types and return values.
|
||||
// Middleware is applied in reverse order (last added, first executed).
|
||||
// Panics if the function signature is invalid or cannot be wrapped.
|
||||
func (m Wrapper) Endpoint(f any) grpc.HandlerFunc {
|
||||
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
handler := caller.Handle
|
||||
for i := range slices.Backward(m.Middlewares) {
|
||||
handler = m.Middlewares[i](handler)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithMiddlewares returns a new Wrapper with additional middleware appended.
|
||||
// The original Wrapper is not modified.
|
||||
func (m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper {
|
||||
return Wrapper{
|
||||
ParamMappers: m.ParamMappers,
|
||||
BodyExtractor: m.BodyExtractor,
|
||||
BodyMapper: m.BodyMapper,
|
||||
Middlewares: append(m.Middlewares, middlewares...),
|
||||
}
|
||||
}
|
||||
-241
@@ -1,241 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.31.0
|
||||
// protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
structpb "google.golang.org/protobuf/types/known/structpb"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// Types that are assignable to Body:
|
||||
//
|
||||
// *Message_StructBody
|
||||
// *Message_ListBody
|
||||
// *Message_NullBody
|
||||
// *Message_BytesBody
|
||||
Body isMessage_Body `protobuf_oneof:"body"`
|
||||
}
|
||||
|
||||
func (x *Message) Reset() {
|
||||
*x = Message{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Message) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Message) ProtoMessage() {}
|
||||
|
||||
func (x *Message) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Message.ProtoReflect.Descriptor instead.
|
||||
func (*Message) Descriptor() ([]byte, []int) {
|
||||
return file_backed_service_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (m *Message) GetBody() isMessage_Body {
|
||||
if m != nil {
|
||||
return m.Body
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetStructBody() *structpb.Struct {
|
||||
if x, ok := x.GetBody().(*Message_StructBody); ok {
|
||||
return x.StructBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetListBody() *structpb.ListValue {
|
||||
if x, ok := x.GetBody().(*Message_ListBody); ok {
|
||||
return x.ListBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetNullBody() structpb.NullValue {
|
||||
if x, ok := x.GetBody().(*Message_NullBody); ok {
|
||||
return x.NullBody
|
||||
}
|
||||
return structpb.NullValue(0)
|
||||
}
|
||||
|
||||
func (x *Message) GetBytesBody() []byte {
|
||||
if x, ok := x.GetBody().(*Message_BytesBody); ok {
|
||||
return x.BytesBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type isMessage_Body interface {
|
||||
isMessage_Body()
|
||||
}
|
||||
|
||||
type Message_StructBody struct {
|
||||
StructBody *structpb.Struct `protobuf:"bytes,1,opt,name=structBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_ListBody struct {
|
||||
ListBody *structpb.ListValue `protobuf:"bytes,2,opt,name=listBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_NullBody struct {
|
||||
NullBody structpb.NullValue `protobuf:"varint,3,opt,name=NullBody,proto3,enum=google.protobuf.NullValue,oneof"`
|
||||
}
|
||||
|
||||
type Message_BytesBody struct {
|
||||
BytesBody []byte `protobuf:"bytes,4,opt,name=BytesBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
func (*Message_StructBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_ListBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_NullBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_BytesBody) isMessage_Body() {}
|
||||
|
||||
var File_backed_service_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_backed_service_proto_rawDesc = []byte{
|
||||
0x0a, 0x14, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65,
|
||||
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x69, 0x73, 0x70, 0x1a, 0x1c, 0x67, 0x6f, 0x6f,
|
||||
0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72,
|
||||
0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe0, 0x01, 0x0a, 0x07, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42,
|
||||
0x6f, 0x64, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
|
||||
0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75,
|
||||
0x63, 0x74, 0x48, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x6f, 0x64, 0x79,
|
||||
0x12, 0x38, 0x0a, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, 0x01,
|
||||
0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00,
|
||||
0x52, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x38, 0x0a, 0x08, 0x4e, 0x75,
|
||||
0x6c, 0x6c, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x67,
|
||||
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4e,
|
||||
0x75, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, 0x52, 0x08, 0x4e, 0x75, 0x6c, 0x6c,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x12, 0x1e, 0x0a, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73, 0x42, 0x6f, 0x64,
|
||||
0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x42, 0x06, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x32, 0x6c, 0x0a, 0x0e,
|
||||
0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x27,
|
||||
0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e,
|
||||
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d,
|
||||
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65, 0x73,
|
||||
0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x3b,
|
||||
0x69, 0x73, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_backed_service_proto_rawDescOnce sync.Once
|
||||
file_backed_service_proto_rawDescData = file_backed_service_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_backed_service_proto_rawDescGZIP() []byte {
|
||||
file_backed_service_proto_rawDescOnce.Do(func() {
|
||||
file_backed_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_backed_service_proto_rawDescData)
|
||||
})
|
||||
return file_backed_service_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_backed_service_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_backed_service_proto_goTypes = []interface{}{
|
||||
(*Message)(nil), // 0: isp.Message
|
||||
(*structpb.Struct)(nil), // 1: google.protobuf.Struct
|
||||
(*structpb.ListValue)(nil), // 2: google.protobuf.ListValue
|
||||
(structpb.NullValue)(0), // 3: google.protobuf.NullValue
|
||||
}
|
||||
var file_backed_service_proto_depIdxs = []int32{
|
||||
1, // 0: isp.Message.structBody:type_name -> google.protobuf.Struct
|
||||
2, // 1: isp.Message.listBody:type_name -> google.protobuf.ListValue
|
||||
3, // 2: isp.Message.NullBody:type_name -> google.protobuf.NullValue
|
||||
0, // 3: isp.BackendService.Request:input_type -> isp.Message
|
||||
0, // 4: isp.BackendService.RequestStream:input_type -> isp.Message
|
||||
0, // 5: isp.BackendService.Request:output_type -> isp.Message
|
||||
0, // 6: isp.BackendService.RequestStream:output_type -> isp.Message
|
||||
5, // [5:7] is the sub-list for method output_type
|
||||
3, // [3:5] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_backed_service_proto_init() }
|
||||
func file_backed_service_proto_init() {
|
||||
if File_backed_service_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_backed_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Message); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
file_backed_service_proto_msgTypes[0].OneofWrappers = []interface{}{
|
||||
(*Message_StructBody)(nil),
|
||||
(*Message_ListBody)(nil),
|
||||
(*Message_NullBody)(nil),
|
||||
(*Message_BytesBody)(nil),
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_backed_service_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_backed_service_proto_goTypes,
|
||||
DependencyIndexes: file_backed_service_proto_depIdxs,
|
||||
MessageInfos: file_backed_service_proto_msgTypes,
|
||||
}.Build()
|
||||
File_backed_service_proto = out.File
|
||||
file_backed_service_proto_rawDesc = nil
|
||||
file_backed_service_proto_goTypes = nil
|
||||
file_backed_service_proto_depIdxs = nil
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
syntax = "proto3";
|
||||
package isp;
|
||||
// protoc --go_out=plugins=grpc:. *.proto
|
||||
|
||||
option go_package = ".;isp";
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
|
||||
message Message {
|
||||
oneof body {
|
||||
google.protobuf.Struct structBody = 1;
|
||||
google.protobuf.ListValue listBody = 2;
|
||||
google.protobuf.NullValue NullBody = 3;
|
||||
bytes BytesBody = 4;
|
||||
}
|
||||
}
|
||||
|
||||
service BackendService {
|
||||
// ===== SYSTEM =====
|
||||
rpc Request (Message) returns (Message) {}
|
||||
|
||||
rpc RequestStream(stream Message) returns (stream Message) {}
|
||||
}
|
||||
-176
@@ -1,176 +0,0 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.2.0
|
||||
// - protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
// BackendServiceClient is the client API for BackendService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type BackendServiceClient interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
|
||||
RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error)
|
||||
}
|
||||
|
||||
type backendServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewBackendServiceClient(cc grpc.ClientConnInterface) BackendServiceClient {
|
||||
return &backendServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) {
|
||||
out := new(Message)
|
||||
err := c.cc.Invoke(ctx, "/isp.BackendService/Request", in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error) {
|
||||
stream, err := c.cc.NewStream(ctx, &BackendService_ServiceDesc.Streams[0], "/isp.BackendService/RequestStream", opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &backendServiceRequestStreamClient{stream}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamClient interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Send(m *Message) error {
|
||||
return x.ClientStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendServiceServer is the server API for BackendService service.
|
||||
// All implementations must embed UnimplementedBackendServiceServer
|
||||
// for forward compatibility
|
||||
type BackendServiceServer interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(context.Context, *Message) (*Message, error)
|
||||
RequestStream(BackendService_RequestStreamServer) error
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedBackendServiceServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedBackendServiceServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedBackendServiceServer) Request(context.Context, *Message) (*Message, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Request not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) RequestStream(BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "method RequestStream not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) mustEmbedUnimplementedBackendServiceServer() {}
|
||||
|
||||
// UnsafeBackendServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to BackendServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeBackendServiceServer interface {
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
func RegisterBackendServiceServer(s grpc.ServiceRegistrar, srv BackendServiceServer) {
|
||||
s.RegisterService(&BackendService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _BackendService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(Message)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(BackendServiceServer).Request(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: "/isp.BackendService/Request",
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(BackendServiceServer).Request(ctx, req.(*Message))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _BackendService_RequestStream_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
return srv.(BackendServiceServer).RequestStream(&backendServiceRequestStreamServer{stream})
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamServer interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Send(m *Message) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ServerStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendService_ServiceDesc is the grpc.ServiceDesc for BackendService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var BackendService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "isp.BackendService",
|
||||
HandlerType: (*BackendServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Request",
|
||||
Handler: _BackendService_Request_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "RequestStream",
|
||||
Handler: _BackendService_RequestStream_Handler,
|
||||
ServerStreams: true,
|
||||
ClientStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "backed_service.proto",
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ProxyMethodNameHeader is the metadata key used to specify the target endpoint.
|
||||
ProxyMethodNameHeader = "proxy_method_name"
|
||||
)
|
||||
|
||||
// Mux is a request router that dispatches gRPC requests to registered handlers based on endpoint name.
|
||||
// It extracts the endpoint from request metadata and invokes the corresponding HandlerFunc.
|
||||
// Mux implements the BackendServiceServer interface but does not support streaming RPCs.
|
||||
type Mux struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
unaryHandlers map[string]HandlerFunc
|
||||
}
|
||||
|
||||
// NewMux creates a new Mux with an empty handler registry.
|
||||
func NewMux() *Mux {
|
||||
return &Mux{
|
||||
unaryHandlers: make(map[string]HandlerFunc),
|
||||
}
|
||||
}
|
||||
|
||||
// Handle registers a HandlerFunc for the specified endpoint.
|
||||
// Panics if a handler is already registered for the endpoint.
|
||||
// Returns the Mux for method chaining.
|
||||
func (m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux {
|
||||
_, ok := m.unaryHandlers[endpoint]
|
||||
if ok {
|
||||
panic(errors.Errorf("handler for endpoint %v is already provided", endpoint))
|
||||
}
|
||||
m.unaryHandlers[endpoint] = handler
|
||||
return m
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by routing to the registered handler for the endpoint.
|
||||
// The endpoint is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
// Returns an error if metadata is missing, endpoint is not found, or handler fails.
|
||||
func (m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
endpoint, err := StringFromMd(ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handler, ok := m.unaryHandlers[endpoint]
|
||||
if !ok {
|
||||
return nil, status.Errorf(codes.NotFound, "handler not found for endpoint %s", endpoint)
|
||||
}
|
||||
ctx = log.ToContext(ctx, log.String("endpoint", endpoint))
|
||||
return handler(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream returns an unimplemented error for streaming RPCs.
|
||||
// Mux does not support streaming; use a custom implementation for streaming support.
|
||||
func (m *Mux) RequestStream(_ isp.BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "service does not support streaming RPC")
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
// Package grpc provides a gRPC server and client implementation for the ISP kit framework.
|
||||
// It enables building scalable microservices with support for hot-swappable handlers,
|
||||
// middleware integration, and structured authentication via metadata.
|
||||
//
|
||||
// The package supports both unary and streaming RPCs, with built-in features for
|
||||
// request/response logging, metrics collection, and distributed tracing.
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxSizeByte defines the default maximum message size in bytes (64MB).
|
||||
DefaultMaxSizeByte = 64 * 1024 * 1024
|
||||
)
|
||||
|
||||
// service implements the BackendServiceServer interface with hot-swappable handler support.
|
||||
// It uses atomic.Value for thread-safe handler replacement without interrupting in-flight requests.
|
||||
type service struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
delegate atomic.Value
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return nil, errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.Request(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream handles streaming gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) RequestStream(server isp.BackendService_RequestStreamServer) error {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.RequestStream(server)
|
||||
}
|
||||
|
||||
// Server wraps a gRPC server with hot-swappable handler support.
|
||||
// It provides a clean interface for starting, stopping, and upgrading gRPC services
|
||||
// without requiring server restart.
|
||||
type Server struct {
|
||||
server *grpc.Server
|
||||
service *service
|
||||
}
|
||||
|
||||
// DefaultServer creates a new Server with default configuration including 64MB message size limits.
|
||||
// Accepts additional grpc.ServerOption for further customization.
|
||||
// Thread-safe for concurrent use.
|
||||
func DefaultServer(restOptions ...grpc.ServerOption) *Server {
|
||||
opts := append([]grpc.ServerOption{
|
||||
grpc.MaxRecvMsgSize(DefaultMaxSizeByte),
|
||||
grpc.MaxSendMsgSize(DefaultMaxSizeByte),
|
||||
}, restOptions...)
|
||||
return NewServer(opts...)
|
||||
}
|
||||
|
||||
// NewServer creates a new Server with custom gRPC options.
|
||||
// Accepts variadic grpc.ServerOption for full configuration control.
|
||||
// Thread-safe for concurrent use.
|
||||
func NewServer(opts ...grpc.ServerOption) *Server {
|
||||
s := &Server{
|
||||
server: grpc.NewServer(opts...),
|
||||
service: &service{
|
||||
delegate: atomic.Value{},
|
||||
},
|
||||
}
|
||||
isp.RegisterBackendServiceServer(s.server, s.service)
|
||||
return s
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the server, waiting for in-flight requests to complete.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Shutdown() {
|
||||
s.server.GracefulStop()
|
||||
}
|
||||
|
||||
// Upgrade atomically replaces the backend service handler without interrupting in-flight requests.
|
||||
// This enables hot-reload of business logic without server restart.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Upgrade(service isp.BackendServiceServer) {
|
||||
s.service.delegate.Store(service)
|
||||
}
|
||||
|
||||
// ListenAndServe binds the server to the specified TCP address and starts serving.
|
||||
// Returns an error if binding fails or serving encounters a fatal error.
|
||||
func (s *Server) ListenAndServe(address string) error {
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(context.Background(), "tcp", address)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "listen: %s", address)
|
||||
}
|
||||
return s.Serve(listener)
|
||||
}
|
||||
|
||||
// Serve starts serving gRPC requests on the provided listener.
|
||||
// Blocks until the server is stopped or an error occurs.
|
||||
// Returns an error if serving encounters a fatal error.
|
||||
func (s *Server) Serve(listener net.Listener) error {
|
||||
err := s.server.Serve(listener)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "serve grpc")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
# Package `http`
|
||||
|
||||
Пакет `http` предоставляет инструменты для создания и управления HTTP-сервером с поддержкой middleware, обработки
|
||||
запросов и гибкой настройки. Интегрируется с системой логирования и обработки ошибок.
|
||||
|
||||
## Types
|
||||
|
||||
### Server
|
||||
|
||||
Структура Server управляет жизненным циклом HTTP-сервера, включая запуск, остановку и динамическое обновление
|
||||
обработчиков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewServer(logger log.Logger, opts ...ServerOption) *Server`
|
||||
|
||||
Конструктор сервера. Дополнительно принимает опции:
|
||||
|
||||
- `WithServer(server *http.Server) ServerOption` – использование объекта предварительно настроенного HTTP-сервера из
|
||||
стандартной библиотеки `net/http`.
|
||||
|
||||
#### `(s *Server) Upgrade(handler http.Handler)`
|
||||
|
||||
Атомарно заменить текущий обработчик запросов на новый.
|
||||
|
||||
#### `(s *Server) ListenAndServe(address string) error`
|
||||
|
||||
Запустить сервер на указанном адресе.
|
||||
|
||||
#### `(s *Server) Serve(listener net.Listener) error`
|
||||
|
||||
Запустить сервер на существующем listener.
|
||||
|
||||
#### `(s *Server) Shutdown(ctx context.Context) error`
|
||||
|
||||
Остановить сервер, завершив все активные соединения.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
srv := http2.NewServer(logger)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("hello world!!"))
|
||||
})
|
||||
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
_ = srv.Shutdown(context.Background())
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
Generated
Vendored
+8
-15
@@ -1,7 +1,8 @@
|
||||
# Package `apierrors`
|
||||
|
||||
Пакет `apierrors` предоставляет структурированный формат ошибок для gRPC-сервисов с поддержкой кодов ошибок, деталей,
|
||||
уровней логирования и интеграции с gRPC-статусами. Позволяет единообразно обрабатывать бизнес-ошибки и технические сбои.
|
||||
Пакет `apierrors` предоставляет инструменты для создания и управления структурированными ошибками HTTP-API.
|
||||
Ошибки включают код, сообщение, детали и уровень логирования, а также автоматически сериализуются в JSON для ответов
|
||||
клиентам.
|
||||
|
||||
## Types
|
||||
|
||||
@@ -13,14 +14,12 @@
|
||||
|
||||
#### `NewInternalServiceError(err error) Error`
|
||||
|
||||
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с gRPC-статусом 13 (internal), бизнесовым кодом 900 и
|
||||
уровнем
|
||||
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с HTTP-статусом 500, бизнесовым кодом 900 и уровнем
|
||||
логирования error.
|
||||
|
||||
#### `NewBusinessError(errorCode int, errorMessage string, err error) Error`
|
||||
|
||||
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с gRPC-статусом 3 (invalid argument),
|
||||
указанным
|
||||
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с HTTP-статусом 400, указанным
|
||||
бизнесовым кодом и уровнем логирования warn.
|
||||
|
||||
#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error`
|
||||
@@ -31,9 +30,9 @@
|
||||
|
||||
Получить строковое представление ошибки.
|
||||
|
||||
#### `(e Error) GrpcStatusError() error`
|
||||
#### `(e Error) WriteError(w http.ResponseWriter) error`
|
||||
|
||||
Конвертирует ошибку в gRPC-сообщение с сериализованными деталями об ошибке в формате JSON.
|
||||
Сериализует ошибку в JSON и записывает в `http.ResponseWriter`.
|
||||
|
||||
#### `(e Error) WithDetails(details map[string]any) Error`
|
||||
|
||||
@@ -47,12 +46,6 @@
|
||||
|
||||
Получить текущий уровень логирования ошибки
|
||||
|
||||
## Functions
|
||||
|
||||
#### `FromError(err error) *Error`
|
||||
|
||||
Извлекает структурированную бизнесовую ошибку из gRPC-сообщения спрятанного под интерфейс `error`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
@@ -64,7 +57,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
// Package apierrors provides HTTP error handling with structured error responses.
|
||||
// It supports business and internal errors with customizable HTTP status codes,
|
||||
// error codes, and logging levels.
|
||||
package apierrors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// ErrCodeInternal is the default error code for internal service errors.
|
||||
ErrCodeInternal = 900
|
||||
)
|
||||
|
||||
// Error represents a structured HTTP error with an error code, message, and optional details.
|
||||
// It supports custom HTTP status codes, logging levels, and error chaining.
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMessage string
|
||||
Details map[string]any `json:",omitempty"`
|
||||
|
||||
httpStatusCode int
|
||||
cause error
|
||||
level log.Level
|
||||
}
|
||||
|
||||
// NewInternalServiceError creates a new internal service error with HTTP 500 status code.
|
||||
// It logs at Error level and wraps the provided cause error.
|
||||
func NewInternalServiceError(err error) Error {
|
||||
return New(http.StatusInternalServerError, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
|
||||
}
|
||||
|
||||
// NewBusinessError creates a new business error with HTTP 400 status code.
|
||||
// It logs at Warn level and is used for client-side validation or business logic errors.
|
||||
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
|
||||
return New(http.StatusBadRequest, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
// New creates a new Error with the specified HTTP status code, error code, message, and cause.
|
||||
// The default log level is ErrorLevel.
|
||||
func New(
|
||||
httpStatusCode int,
|
||||
errorCode int,
|
||||
errorMessage string,
|
||||
err error,
|
||||
) Error {
|
||||
return Error{
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
httpStatusCode: httpStatusCode,
|
||||
cause: err,
|
||||
level: log.ErrorLevel,
|
||||
}
|
||||
}
|
||||
|
||||
// Error returns a formatted string representation of the error.
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
|
||||
}
|
||||
|
||||
// WriteError writes the error as a JSON response to the http.ResponseWriter.
|
||||
// It sets the Content-Type header to application/json and the appropriate HTTP status code.
|
||||
func (e Error) WriteError(w http.ResponseWriter) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(e.httpStatusCode)
|
||||
err := json.NewEncoder(w).Encode(e)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "json encode error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithDetails adds additional context details to the error.
|
||||
func (e Error) WithDetails(details map[string]any) Error {
|
||||
e.Details = details
|
||||
return e
|
||||
}
|
||||
|
||||
// WithLogLevel sets the logging level for this error.
|
||||
func (e Error) WithLogLevel(level log.Level) Error {
|
||||
e.level = level
|
||||
return e
|
||||
}
|
||||
|
||||
// LogLevel returns the logging level associated with this error.
|
||||
func (e Error) LogLevel() log.Level {
|
||||
return e.level
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Package http provides core HTTP server functionality and types for building REST and SOAP services.
|
||||
// It includes a server implementation, handler wrapper, and middleware support for request processing.
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// HandlerFunc is the signature for HTTP handlers that process requests in a context-aware manner.
|
||||
// Handlers should return an error to indicate processing failure.
|
||||
type HandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
|
||||
|
||||
// Middleware is a function that wraps a HandlerFunc to add cross-cutting concerns
|
||||
// such as logging, authentication, or metrics collection.
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
# Package `endpoint`
|
||||
|
||||
Пакет `endpoint` предоставляет инструменты для создания HTTP-обработчиков с поддержкой middleware, валидации данных,
|
||||
логирования и метрик. Упрощает разработку API, автоматизируя рутинные задачи.
|
||||
|
||||
## Types
|
||||
|
||||
### Wrapper
|
||||
|
||||
Структура для создания оберток вокруг обработчиков. Объединяет:
|
||||
|
||||
- Параметры функции (контекст, запрос, тело и т.д.).
|
||||
- Middleware (логирование, метрики, трейсинг).
|
||||
- Валидацию и сериализацию данных.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, logger log.Logger) Wrapper`
|
||||
|
||||
Конструктор обертки с указанными параметрами.
|
||||
|
||||
#### `(m Wrapper) Endpoint(f any) http.HandlerFunc`
|
||||
|
||||
Преобразовать функцию-обработчик в HTTP-обработчик.
|
||||
|
||||
#### `(m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper`
|
||||
|
||||
Билдер-метод для добавления middleware в обертку.
|
||||
|
||||
### JsonRequestExtractor
|
||||
|
||||
Извлекает JSON из тела запроса и валидирует его с помощью объекта, реализующего интерфейс `Validator`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`(j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)`
|
||||
|
||||
Десериализовать JSON и проверить данные через `Validator`.
|
||||
|
||||
### JsonResponseMapper
|
||||
|
||||
Сериализует ответ в JSON и добавляет заголовки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error`
|
||||
|
||||
Упаковка результата в JSON-ответ.
|
||||
|
||||
### Caller
|
||||
|
||||
Структура `Caller` предоставляет механизм для вызова функций-обработчиков HTTP-запросов, автоматически преобразуя
|
||||
параметры запроса в аргументы функции. Интегрируется с валидацией, извлечением данных и middleware.
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`NewCaller(f any, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)`
|
||||
|
||||
Создает экземпляр `Caller` для функции-обработчика.
|
||||
|
||||
#### `(h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error`
|
||||
|
||||
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
|
||||
|
||||
|
||||
## Middlewares
|
||||
|
||||
### `MaxRequestBodySize`
|
||||
|
||||
Ограничивает размер тела запроса (по умолчанию 64 МБ).
|
||||
|
||||
### `RequestId`
|
||||
|
||||
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
|
||||
|
||||
### `DecodeRequest`
|
||||
Декодирует запрос при помощи переданного codec, если заголовок `Content-Encoding` совпадает с типом codec.
|
||||
|
||||
### `LogMiddleware`
|
||||
|
||||
Логирует данные запросов и ответов.
|
||||
|
||||
### `Metrics`
|
||||
|
||||
Собирает метрики: время выполнения, статус-коды, размеры тел.
|
||||
|
||||
### `Tracing`
|
||||
|
||||
Интеграция с трейсингом (OpenTelemetry).
|
||||
|
||||
### `EncodeResponse`
|
||||
|
||||
Кодирует ответ при помощи переданного codec, если заголовок `Accept-Encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
|
||||
|
||||
### `ErrorHandler`
|
||||
|
||||
Перехватывает и обрабатывает ошибки. Ошибки типа `HttpError` возвращают структурированный ответ.
|
||||
Остальные ошибки логируются и возвращаются как 500 Internal Server Error.
|
||||
|
||||
### `Recovery`
|
||||
|
||||
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `MaxRequestBodySize`
|
||||
- `RequestId`
|
||||
- `LogMiddleware`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
#### `DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
- `MaxRequestBodySize`
|
||||
- `RequestId`
|
||||
- `DecodeRequest`
|
||||
- `LogMiddleware`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `EncodeResponse`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type userRequest struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
Id int
|
||||
}
|
||||
|
||||
func foo(ctx context.Context, req userRequest) (userResponse, error) {
|
||||
/* put here some business logic */
|
||||
return userResponse{Id: 88}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
srv := http.NewServer(logger)
|
||||
|
||||
wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
|
||||
r := router.New()
|
||||
r.POST("/foo", wrapper.Endpoint(foo))
|
||||
|
||||
srv.Upgrade(r)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
_ = srv.Shutdown(context.Background())
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Codec usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type userRequest struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
Id int
|
||||
}
|
||||
|
||||
func foo(ctx context.Context, req userRequest) (userResponse, error) {
|
||||
/* put here some business logic */
|
||||
return userResponse{Id: 88}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
srv := http.NewServer(logger)
|
||||
|
||||
wrapper := endpoint.DefaultCodecWrapper(logger, httplog.Log(logger, true))
|
||||
r := router.New()
|
||||
r.POST("/foo", wrapper.Endpoint(foo))
|
||||
|
||||
srv.Upgrade(r)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
_ = srv.Shutdown(context.Background())
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
# Package `buffer`
|
||||
|
||||
Пакет `buffer` предоставляет инструменты для буферизации HTTP-запросов и ответов. Используется в middleware для
|
||||
логирования, метрик и других задач, требующих доступа к телам запросов и ответов без их модификации.
|
||||
|
||||
## Types
|
||||
|
||||
### Buffer
|
||||
|
||||
Структура для перехвата и буферизации данных HTTP-ответа. Реализует интерфейс `http.ResponseWriter`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New() *Buffer`
|
||||
|
||||
Конструктор буфера. Инициализирует внутренние буферы для тела запроса и ответа.
|
||||
|
||||
#### `(m *Buffer) Reset(w http.ResponseWriter)`
|
||||
|
||||
Сбрасывает состояние буфера и привязывает его к новому `http.ResponseWriter`.
|
||||
|
||||
#### `(m *Buffer) Write(b []byte) (int, error)`
|
||||
|
||||
Перехватывает данные, записываемые в ответ, и сохраняет их в буфер.
|
||||
|
||||
#### `(m *Buffer) WriteHeader(statusCode int)`
|
||||
|
||||
Фиксирует статус-код ответа.
|
||||
|
||||
#### `(m *Buffer) ResponseBody() []byte`
|
||||
|
||||
Возвращает тело ответа в виде байтов из буфера.
|
||||
|
||||
#### `(m *Buffer) RequestBody() []byte`
|
||||
|
||||
Возвращает тело запроса в виде байтов из буфера.
|
||||
|
||||
#### `(m *Buffer) ReadRequestBody(r io.Reader) error`
|
||||
|
||||
Читает тело запроса и сохраняет его в буфер.
|
||||
|
||||
#### `(m *Buffer) StatusCode() int`
|
||||
|
||||
Возвращает статус-код ответа. Если статус-код не был еще записан, вернется 200 OK.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Acquire(w http.ResponseWriter) *Buffer`
|
||||
|
||||
Берет буфер из пула и инициализирует его для работы с указанным `http.ResponseWriter`.
|
||||
|
||||
#### `Release(w *Buffer)`
|
||||
|
||||
Возвращает буфер в пул для повторного использования.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/endpoint/buffer"
|
||||
)
|
||||
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
/* get buffer from pool */
|
||||
buf := buffer.Acquire(w)
|
||||
defer buffer.Release(buf)
|
||||
|
||||
/* read request body */
|
||||
_ = buf.ReadRequestBody(r.Body)
|
||||
r.Body = buffer.NewRequestBody(buf.RequestBody())
|
||||
|
||||
next.ServeHTTP(buf, r)
|
||||
|
||||
/* log response body */
|
||||
responseBody := buf.ResponseBody()
|
||||
log.Printf("Response: %s\n", responseBody)
|
||||
})
|
||||
}
|
||||
|
||||
```
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
// Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
|
||||
// It is used for logging and metrics collection in HTTP middleware.
|
||||
package buffer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultBufferSize is the initial buffer size in bytes.
|
||||
defaultBufferSize = 1024
|
||||
)
|
||||
|
||||
// Buffer wraps http.ResponseWriter to capture request and response bodies.
|
||||
// It is commonly used in middleware for logging and metrics collection.
|
||||
type Buffer struct {
|
||||
http.ResponseWriter
|
||||
|
||||
requestBuffer *bytes.Buffer
|
||||
responseBuffer *bytes.Buffer
|
||||
statusCode int
|
||||
}
|
||||
|
||||
// New creates a new Buffer with initialized request and response buffers.
|
||||
func New() *Buffer {
|
||||
return &Buffer{
|
||||
requestBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
|
||||
responseBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
|
||||
}
|
||||
}
|
||||
|
||||
// Reset reinitializes the buffer with a new ResponseWriter and clears internal state.
|
||||
// It should be called before reusing a pooled Buffer.
|
||||
func (m *Buffer) Reset(w http.ResponseWriter) {
|
||||
m.ResponseWriter = w
|
||||
m.statusCode = 0
|
||||
m.responseBuffer.Reset()
|
||||
m.requestBuffer.Reset()
|
||||
}
|
||||
|
||||
// Write writes data to both the underlying ResponseWriter and the response buffer.
|
||||
// It returns the number of bytes written and any error encountered.
|
||||
func (m *Buffer) Write(b []byte) (int, error) {
|
||||
n, err := m.ResponseWriter.Write(b)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
n, err = m.responseBuffer.Write(b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
|
||||
func (m *Buffer) WriteHeader(statusCode int) {
|
||||
m.statusCode = statusCode
|
||||
m.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
// ResponseBody returns the captured response body as a byte slice.
|
||||
func (m *Buffer) ResponseBody() []byte {
|
||||
return m.responseBuffer.Bytes()
|
||||
}
|
||||
|
||||
// RequestBody returns the captured request body as a byte slice.
|
||||
func (m *Buffer) RequestBody() []byte {
|
||||
return m.requestBuffer.Bytes()
|
||||
}
|
||||
|
||||
// ReadRequestBody reads the entire request body into the buffer.
|
||||
// It returns an error if the read operation fails.
|
||||
func (m *Buffer) ReadRequestBody(r io.Reader) error {
|
||||
_, err := io.Copy(m.requestBuffer, r)
|
||||
return err
|
||||
}
|
||||
|
||||
// StatusCode returns the captured status code, or http.StatusOK if not set.
|
||||
func (m *Buffer) StatusCode() int {
|
||||
if m.statusCode == 0 {
|
||||
return http.StatusOK
|
||||
}
|
||||
return m.statusCode
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package buffer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// pool is a global sync.Pool for reusing Buffer instances.
|
||||
// It reduces memory allocation overhead by pooling Buffer objects.
|
||||
var pool = sync.Pool{
|
||||
New: func() any {
|
||||
return New()
|
||||
},
|
||||
}
|
||||
|
||||
// Acquire retrieves a Buffer from the pool and initializes it with the given ResponseWriter.
|
||||
// It is safe for concurrent use and should be paired with Release.
|
||||
func Acquire(w http.ResponseWriter) *Buffer {
|
||||
var buffer *Buffer
|
||||
var ok bool
|
||||
buffer, ok = pool.Get().(*Buffer)
|
||||
if !ok {
|
||||
buffer = New()
|
||||
}
|
||||
buffer.Reset(w)
|
||||
return buffer
|
||||
}
|
||||
|
||||
// Release returns a Buffer to the pool for reuse.
|
||||
// It should be called after the Buffer is no longer needed.
|
||||
func Release(w *Buffer) {
|
||||
pool.Put(w)
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package buffer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
)
|
||||
|
||||
// RequestBody wraps a bytes.Buffer to provide an io.ReadCloser for request body replay.
|
||||
// It is used when the request body needs to be read multiple times (e.g., for logging).
|
||||
type RequestBody struct {
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
// NewRequestBody creates a new RequestBody from a byte slice.
|
||||
func NewRequestBody(body []byte) RequestBody {
|
||||
return RequestBody{
|
||||
body: bytes.NewBuffer(body),
|
||||
}
|
||||
}
|
||||
|
||||
// Read reads data from the underlying buffer into p.
|
||||
// It returns the number of bytes read and any error encountered.
|
||||
func (r RequestBody) Read(p []byte) (n int, err error) {
|
||||
return r.body.Read(p)
|
||||
}
|
||||
|
||||
// Close is a no-op to satisfy the io.ReadCloser interface.
|
||||
func (r RequestBody) Close() error {
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
+18
-19
@@ -2,21 +2,21 @@ package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// param represents a single parameter to be injected into a wrapped function.
|
||||
// param represents a function parameter that can be built from the request context.
|
||||
type param struct {
|
||||
index int
|
||||
builder ParamBuilder
|
||||
}
|
||||
|
||||
// Caller wraps a function for gRPC invocation using reflection.
|
||||
// It analyzes the function signature, injects dependencies, and handles
|
||||
// request/response marshaling automatically.
|
||||
// Caller uses reflection to wrap arbitrary functions as HTTP handlers.
|
||||
// It automatically extracts request body, builds parameters from the context,
|
||||
// and maps return values to the response.
|
||||
type Caller struct {
|
||||
bodyExtractor RequestBodyExtractor
|
||||
bodyMapper ResponseBodyMapper
|
||||
@@ -32,9 +32,9 @@ type Caller struct {
|
||||
errorIndex int
|
||||
}
|
||||
|
||||
// NewCaller creates a new Caller for the specified function.
|
||||
// Analyzes the function signature to determine parameter types and return values.
|
||||
// Returns an error if the input is not a function or if parameter types cannot be resolved.
|
||||
// NewCaller creates a new Caller that wraps the provided function.
|
||||
// It analyzes the function signature and configures parameter extraction and result mapping.
|
||||
// Returns an error if the provided value is not a function or has invalid parameter types.
|
||||
func NewCaller(
|
||||
f any,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
@@ -88,24 +88,23 @@ func NewCaller(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes the wrapped function with the provided context and message.
|
||||
// Injects parameters, extracts request body, calls the function, and maps the result.
|
||||
// Returns the response message and any error from the function or parameter extraction.
|
||||
func (h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
// Handle invokes the wrapped function with extracted parameters and maps the result.
|
||||
// It returns an error if parameter extraction fails or the function returns an error.
|
||||
func (h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
args := make([]reflect.Value, h.paramsCount)
|
||||
|
||||
if h.reqBodyIndex != -1 {
|
||||
value, err := h.bodyExtractor.Extract(ctx, message, h.reqBodyType)
|
||||
value, err := h.bodyExtractor.Extract(ctx, r.Body, h.reqBodyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
args[h.reqBodyIndex] = value
|
||||
}
|
||||
|
||||
for _, p := range h.params {
|
||||
value, err := p.builder(ctx, message)
|
||||
value, err := p.builder(ctx, w, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
args[p.index] = reflect.ValueOf(value)
|
||||
}
|
||||
@@ -113,12 +112,12 @@ func (h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message
|
||||
out := h.handler.Call(args)
|
||||
|
||||
if h.hasError && !out[h.errorIndex].IsNil() {
|
||||
return nil, out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
|
||||
return out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
|
||||
}
|
||||
|
||||
if h.hasResult {
|
||||
return h.bodyMapper.Map(out[0].Interface())
|
||||
return h.bodyMapper.Map(ctx, out[0].Interface(), w)
|
||||
}
|
||||
|
||||
return nil, nil // nolint:nilnil
|
||||
return nil
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
)
|
||||
|
||||
type DecodeCodec interface {
|
||||
Type() string
|
||||
Decode(r io.ReadCloser) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
const (
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
// DecodeRequest returns middleware that transparently handles encoded requests.
|
||||
//
|
||||
// If Content-Encoding matches codec, request body is decoded.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see decoded data.
|
||||
func DecodeRequest(codec DecodeCodec) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
if r.Header.Get("Content-Encoding") == codec.Type() {
|
||||
decoded, err := codec.Decode(r.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.Body = decoded
|
||||
r.Header.Del("Content-Encoding")
|
||||
r.Header.Del("Content-Length")
|
||||
}
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type EncodeCodec interface {
|
||||
Type() string
|
||||
Encode(w io.Writer) (io.WriteCloser, error)
|
||||
}
|
||||
|
||||
// EncodeResponse returns middleware that transparently handles response encoding.
|
||||
//
|
||||
// If client supports Accept-Encoding and response body size > encodeThresholdBytes,
|
||||
// the response is encoded using codec.
|
||||
//
|
||||
// The middleware finalizes the response after the handler returns. It may
|
||||
// implicitly call WriteHeader(http.StatusOK) and flush buffered response data
|
||||
// even if the handler never calls Write or WriteHeader.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see plain data.
|
||||
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
if !acceptsEncoding(r.Header.Get("Accept-Encoding"), codec.Type()) {
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
|
||||
cw := newEncoderWriter(w, codec, encodeThresholdBytes)
|
||||
|
||||
err := next(ctx, cw, r)
|
||||
closeErr := cw.Close()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type encoderWriter struct {
|
||||
http.ResponseWriter
|
||||
|
||||
codec EncodeCodec
|
||||
|
||||
buffer bytes.Buffer
|
||||
encodeThreshold int
|
||||
|
||||
writer io.WriteCloser
|
||||
status int
|
||||
}
|
||||
|
||||
func newEncoderWriter(w http.ResponseWriter, codec EncodeCodec, encodeThreshold int) *encoderWriter {
|
||||
return &encoderWriter{
|
||||
ResponseWriter: w,
|
||||
codec: codec,
|
||||
encodeThreshold: encodeThreshold,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *encoderWriter) WriteHeader(code int) {
|
||||
if w.status != 0 {
|
||||
return
|
||||
}
|
||||
w.status = code
|
||||
}
|
||||
|
||||
func (w *encoderWriter) Write(b []byte) (int, error) {
|
||||
if w.writer != nil {
|
||||
return w.writer.Write(b)
|
||||
}
|
||||
|
||||
// fast path: big first write
|
||||
if w.buffer.Len() == 0 && len(b) > w.encodeThreshold {
|
||||
return w.startEncoding(b)
|
||||
}
|
||||
|
||||
n, err := w.buffer.Write(b)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
if w.buffer.Len() > w.encodeThreshold {
|
||||
data := append([]byte(nil), w.buffer.Bytes()...)
|
||||
w.buffer.Reset()
|
||||
|
||||
return w.startEncoding(data)
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (w *encoderWriter) Close() error {
|
||||
if w.writer != nil {
|
||||
return w.writer.Close()
|
||||
}
|
||||
|
||||
status := w.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
|
||||
_, err := w.ResponseWriter.Write(w.buffer.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
// Hijack implements http.Hijacker.
|
||||
//
|
||||
// Hijacking is only allowed before the response has started (no buffered or
|
||||
// encoded data). Once any response data has been written or encoding has been
|
||||
// triggered, hijacking is disallowed to prevent losing buffered state and to
|
||||
// preserve response integrity.
|
||||
func (w *encoderWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
if w.writer != nil || w.buffer.Len() > 0 || w.status != 0 {
|
||||
return nil, nil, errors.New("encoderWriter: hijack not allowed after response started")
|
||||
}
|
||||
|
||||
upstream, ok := w.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("encoderWriter: upstream writer doesn't implement Hijack")
|
||||
}
|
||||
|
||||
return upstream.Hijack()
|
||||
}
|
||||
|
||||
func (w *encoderWriter) startEncoding(b []byte) (int, error) {
|
||||
writer, err := w.codec.Encode(w.ResponseWriter)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
w.writer = writer
|
||||
|
||||
h := w.Header()
|
||||
h.Set("Content-Encoding", w.codec.Type())
|
||||
h.Add("Vary", "Accept-Encoding")
|
||||
h.Del("Content-Length")
|
||||
|
||||
status := w.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
|
||||
return w.writer.Write(b)
|
||||
}
|
||||
|
||||
func acceptsEncoding(header, encoding string) bool {
|
||||
for part := range strings.SplitSeq(header, ",") {
|
||||
if strings.TrimSpace(part) == encoding {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// DefaultWrapper creates a pre-configured Wrapper with common middleware and settings.
|
||||
// It includes request logging, metrics collection, tracing, error handling, and recovery.
|
||||
// The default maximum request body size is 64MB.
|
||||
func DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
ResponseWriterParam(),
|
||||
RequestParam(),
|
||||
}
|
||||
middlewares := append(
|
||||
[]http.Middleware{
|
||||
MaxRequestBodySize(defaultMaxRequestBodySize),
|
||||
RequestId(),
|
||||
http.Middleware(logMiddleware),
|
||||
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
logger,
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
|
||||
// DefaultCodecWrapper creates a pre-configured Wrapper with common middleware and settings.
|
||||
// It includes request logging, encode response, decode request, metrics collection, tracing, error handling, and recovery.
|
||||
// The default maximum request body size is 64MB.
|
||||
func DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
ResponseWriterParam(),
|
||||
RequestParam(),
|
||||
}
|
||||
codec := codec.Default
|
||||
middlewares := append(
|
||||
[]http.Middleware{
|
||||
MaxRequestBodySize(defaultMaxRequestBodySize),
|
||||
RequestId(),
|
||||
DecodeRequest(codec),
|
||||
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
EncodeResponse(codec, defaultEncodeThreshold),
|
||||
http.Middleware(logMiddleware),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
logger,
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
# Package `httplog`
|
||||
|
||||
Пакет `httplog` предоставляет middleware для логирования HTTP-запросов и ответов. Поддерживает гибкую настройку: выбор
|
||||
типов контента для логирования тела, управление детализацией и интеграцию с буферизацией данных.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) endpoint.LogMiddleware`
|
||||
|
||||
Создает middleware с базовыми настройками:
|
||||
|
||||
- Логирует тело запроса/ответа, если `logBody = true`.
|
||||
- По умолчанию логирует только для `application/json` и `text/xml`.
|
||||
|
||||
#### `CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware`
|
||||
|
||||
Создает middleware с базовыми настройками:
|
||||
|
||||
- Логирует тело запроса/ответа, если `logBody = true`.
|
||||
- По умолчанию логирует только для `application/json` и `text/xml`.
|
||||
- Собирает запрос и ответ в 1 лог.
|
||||
|
||||
#### `LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware`
|
||||
|
||||
Создает middleware с кастомными настройками через опции:
|
||||
|
||||
- `WithContentTypes(logBodyContentTypes []string) Option` – Задает типы контента, для которых логируется тело (например,
|
||||
`application/json`).
|
||||
- `WithLogBody(logBody bool) Option` – Включает/отключает логирование тела запроса и ответа.
|
||||
- `WithLogResponseBody(logResponseBody bool) Option` – Включает/отключает логирование тела ответа.
|
||||
- `WithLogRequestBody(logRequestBody bool) Option` – Включает/отключает логирование тела запроса.
|
||||
- `WithCombinedLog(enable bool) Option` – Включает/отключает сборку запроса/ответа в 1 лог.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default log middleware
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
/* create wrapper with default logging middleware */
|
||||
wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Customize log middleware
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
/* create wrapper with custom logging middleware */
|
||||
wrapper := endpoint.DefaultWrapper(logger, httplog.LogWithOptions(
|
||||
logger,
|
||||
httplog.WithLogRequestBody(true), // enable logging request body
|
||||
httplog.WithLogResponseBody(false), // disable logging response body
|
||||
httplog.WithContentTypes([]string{"application/custom"}), // only for `application/custom` content-type
|
||||
))
|
||||
}
|
||||
|
||||
```
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
// Package httplog provides HTTP request/response logging middleware.
|
||||
// It supports separate request and response body logging, combined logging,
|
||||
// and content-type filtering.
|
||||
package httplog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/buffer"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// applicationNameHeader is the HTTP header for base64-encoded application name.
|
||||
applicationNameHeader = "X-Application-Name"
|
||||
// applicationIdHeader is the HTTP header for application identity (numeric ID).
|
||||
applicationIdHeader = "X-Application-Identity"
|
||||
)
|
||||
|
||||
var (
|
||||
// defaultLogBodyContentTypes specifies the content types for which body logging is enabled.
|
||||
defaultLogBodyContentTypes = []string{
|
||||
"application/json",
|
||||
"text/xml",
|
||||
}
|
||||
)
|
||||
|
||||
// logConfig holds the configuration for the logging middleware.
|
||||
type logConfig struct {
|
||||
logBodyContentTypes []string
|
||||
logRequestBody bool
|
||||
logResponseBody bool
|
||||
combinedLog bool
|
||||
}
|
||||
|
||||
// Log creates a logging middleware that logs requests and responses separately.
|
||||
// If logBody is true, it logs request and response bodies for supported content types.
|
||||
func Log(logger log.Logger, logBody bool) endpoint.LogMiddleware {
|
||||
cfg := &logConfig{
|
||||
logBodyContentTypes: defaultLogBodyContentTypes,
|
||||
logRequestBody: logBody,
|
||||
logResponseBody: logBody,
|
||||
}
|
||||
return middleware(logger, cfg)
|
||||
}
|
||||
|
||||
// CombinedLog creates a logging middleware that logs requests and responses in a single entry.
|
||||
// If logBody is true, it logs request and response bodies for supported content types.
|
||||
func CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware {
|
||||
cfg := &logConfig{
|
||||
logBodyContentTypes: defaultLogBodyContentTypes,
|
||||
logRequestBody: logBody,
|
||||
logResponseBody: logBody,
|
||||
}
|
||||
return combinedLogMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// LogWithOptions creates a logging middleware with custom configuration options.
|
||||
// By default, body logging is disabled. Use options like WithLogBody, WithCombinedLog
|
||||
// to customize the behavior.
|
||||
func LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware {
|
||||
cfg := &logConfig{
|
||||
logBodyContentTypes: defaultLogBodyContentTypes,
|
||||
logRequestBody: false,
|
||||
logResponseBody: false,
|
||||
combinedLog: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
if cfg.combinedLog {
|
||||
return combinedLogMiddleware(logger, cfg)
|
||||
}
|
||||
return middleware(logger, cfg)
|
||||
}
|
||||
|
||||
// middleware creates a logging middleware that logs requests and responses separately.
|
||||
func middleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
buf := buffer.Acquire(w)
|
||||
defer buffer.Release(buf)
|
||||
|
||||
now := time.Now()
|
||||
requestLogFields := []log.Field{
|
||||
log.String("method", r.Method),
|
||||
log.String("url", r.URL.String()),
|
||||
}
|
||||
|
||||
requestContentType := r.Header.Get("Content-Type")
|
||||
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
|
||||
err := buf.ReadRequestBody(r.Body)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "read request body for logging")
|
||||
}
|
||||
err = r.Body.Close()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "close request reader")
|
||||
}
|
||||
r.Body = buffer.NewRequestBody(buf.RequestBody())
|
||||
|
||||
requestLogFields = append(requestLogFields, log.ByteString("requestBody", buf.RequestBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "http handler: request", requestLogFields...)
|
||||
|
||||
err := next(ctx, buf, r)
|
||||
|
||||
responseLogFields := []log.Field{
|
||||
log.Int("statusCode", buf.StatusCode()),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
}
|
||||
|
||||
responseContentType := buf.Header().Get("Content-Type")
|
||||
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
|
||||
responseLogFields = append(responseLogFields, log.ByteString("responseBody", buf.ResponseBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "http handler: response", responseLogFields...)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// combinedLogMiddleware creates a logging middleware that logs requests and responses in a single entry.
|
||||
func combinedLogMiddleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
buf := buffer.Acquire(w)
|
||||
defer buffer.Release(buf)
|
||||
|
||||
now := time.Now()
|
||||
logFields := []log.Field{
|
||||
log.String("method", r.Method),
|
||||
log.String("url", r.URL.String()),
|
||||
}
|
||||
logFields = append(logFields, applicationLogFields(r)...)
|
||||
|
||||
requestContentType := r.Header.Get("Content-Type")
|
||||
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
|
||||
err := buf.ReadRequestBody(r.Body)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "read request body for logging")
|
||||
}
|
||||
err = r.Body.Close()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "close request reader")
|
||||
}
|
||||
r.Body = buffer.NewRequestBody(buf.RequestBody())
|
||||
|
||||
logFields = append(logFields, log.ByteString("requestBody", buf.RequestBody()))
|
||||
}
|
||||
|
||||
err := next(ctx, buf, r)
|
||||
|
||||
logFields = append(logFields,
|
||||
log.Int("statusCode", buf.StatusCode()),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
responseContentType := buf.Header().Get("Content-Type")
|
||||
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
|
||||
logFields = append(logFields, log.ByteString("responseBody", buf.ResponseBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "http handler: log", logFields...)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// matchContentType checks if the given content type matches any of the available content types.
|
||||
// It uses prefix matching to handle content types with parameters (e.g., "application/json; charset=utf-8").
|
||||
func matchContentType(contentType string, availableContentTypes []string) bool {
|
||||
for _, content := range availableContentTypes {
|
||||
if strings.HasPrefix(contentType, content) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// applicationLogFields extracts application-related log fields from the request.
|
||||
// It decodes the base64-encoded application name and parses the application ID.
|
||||
func applicationLogFields(r *http.Request) []log.Field {
|
||||
logFields := make([]log.Field, 0)
|
||||
appName := r.Header.Get(applicationNameHeader)
|
||||
if appName != "" {
|
||||
decodedName, err := base64.StdEncoding.DecodeString(appName)
|
||||
if err == nil {
|
||||
logFields = append(logFields, log.String("applicationName", string(decodedName)))
|
||||
}
|
||||
}
|
||||
|
||||
appId := r.Header.Get(applicationIdHeader)
|
||||
if appId == "" {
|
||||
return logFields
|
||||
}
|
||||
|
||||
intAppId, err := strconv.Atoi(appId)
|
||||
if err == nil {
|
||||
logFields = append(logFields, log.Int("applicationId", intAppId))
|
||||
}
|
||||
return logFields
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package httplog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
)
|
||||
|
||||
// Noop returns a no-operation logging middleware that simply passes through requests.
|
||||
// It is useful as a placeholder or for testing when logging is not needed.
|
||||
func Noop() endpoint.LogMiddleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package httplog
|
||||
|
||||
// Option is a function that configures the logConfig.
|
||||
type Option func(cfg *logConfig)
|
||||
|
||||
// WithContentTypes sets the content types for which request and response bodies will be logged.
|
||||
// Content types are matched using prefix comparison (e.g., "application/json" matches "application/json; charset=utf-8").
|
||||
func WithContentTypes(logBodyContentTypes []string) Option {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logBodyContentTypes = logBodyContentTypes
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogBody is a shortcut to enable both request and response body logging.
|
||||
func WithLogBody(logBody bool) Option {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logBody
|
||||
cfg.logRequestBody = logBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogResponseBody enables or disables response body logging.
|
||||
func WithLogResponseBody(logResponseBody bool) Option {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logResponseBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogRequestBody enables or disables request body logging.
|
||||
func WithLogRequestBody(logRequestBody bool) Option {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logRequestBody = logRequestBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithCombinedLog enables or disables single combined log entry for request and response.
|
||||
// When enabled, the middleware logs request and response in a single log entry instead of two separate entries.
|
||||
func WithCombinedLog(enable bool) Option {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.combinedLog = enable
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// Validator validates a value and returns whether it's valid along with field-level error details.
|
||||
type Validator interface {
|
||||
// Validate returns true if valid and a map of field names to error messages.
|
||||
Validate(value any) (bool, map[string]string)
|
||||
}
|
||||
|
||||
// JsonRequestExtractor extracts and validates JSON request bodies.
|
||||
// It decodes JSON, validates the result, and returns business errors for invalid input.
|
||||
type JsonRequestExtractor struct {
|
||||
Validator Validator
|
||||
}
|
||||
|
||||
// Extract decodes the JSON request body into a reflect.Value of the specified type.
|
||||
// It validates the decoded value and returns a business error if validation fails.
|
||||
func (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error) {
|
||||
instance := reflect.New(reqBodyType)
|
||||
err := j.extract(reader, instance.Interface())
|
||||
if err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
|
||||
elem := instance.Elem()
|
||||
err = j.validate(elem.Interface())
|
||||
if err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
|
||||
return elem, nil
|
||||
}
|
||||
|
||||
// ExtractV2 decodes the JSON request body into the provided pointer.
|
||||
// It validates the decoded value and returns a business error if validation fails.
|
||||
func (j JsonRequestExtractor) ExtractV2(_ context.Context, reader io.Reader, ptr any) error {
|
||||
err := j.extract(reader, ptr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return j.validate(ptr)
|
||||
}
|
||||
|
||||
// extract decodes JSON from the reader into the target pointer.
|
||||
// It returns a business error with HTTP 400 status for invalid JSON.
|
||||
func (j JsonRequestExtractor) extract(reader io.Reader, ptr any) error {
|
||||
err := json.NewDecoder(reader).Decode(ptr)
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "unmarshal json request body")
|
||||
return apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validate validates the decoded value using the configured validator.
|
||||
// It returns a business error with validation details if validation fails.
|
||||
func (j JsonRequestExtractor) validate(v any) error {
|
||||
ok, details := j.Validator.Validate(v)
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
formattedDetails := formatDetails(details)
|
||||
return apierrors.NewBusinessError(
|
||||
http.StatusBadRequest,
|
||||
"invalid request body",
|
||||
errors.Errorf("validation errors: %v", formattedDetails),
|
||||
).WithDetails(formattedDetails)
|
||||
}
|
||||
|
||||
// formatDetails converts validation error details by lowercasing the first letter of each field name.
|
||||
func formatDetails(details map[string]string) map[string]any {
|
||||
result := make(map[string]any, len(details))
|
||||
for k, v := range details {
|
||||
arr := []rune(k)
|
||||
arr[0] = unicode.ToLower(arr[0])
|
||||
result[string(arr)] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
// JsonResponseMapper maps response objects to JSON format.
|
||||
// It sets the Content-Type header to application/json and includes the request ID in response headers.
|
||||
type JsonResponseMapper struct {
|
||||
}
|
||||
|
||||
// Map marshals the result to JSON and writes it to the http.ResponseWriter.
|
||||
// It skips nil results and includes the request ID in the response headers if available.
|
||||
func (j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error {
|
||||
reqId := requestid.FromContext(ctx)
|
||||
if reqId != "" {
|
||||
w.Header().Set(requestid.Header, reqId)
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
err := json.EncodeInto(w, result)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/buffer"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
)
|
||||
|
||||
// scSource is an interface for retrieving the HTTP status code from a response.
|
||||
type scSource interface {
|
||||
StatusCode() int
|
||||
}
|
||||
|
||||
// writerWrapper wraps http.ResponseWriter to capture the status code.
|
||||
// It defaults to http.StatusOK if WriteHeader is not called.
|
||||
type writerWrapper struct {
|
||||
http.ResponseWriter
|
||||
|
||||
statusCode int
|
||||
}
|
||||
|
||||
// StatusCode returns the captured status code, or http.StatusOK if not set.
|
||||
func (w *writerWrapper) StatusCode() int {
|
||||
if w.statusCode == 0 {
|
||||
return http.StatusOK
|
||||
}
|
||||
return w.statusCode
|
||||
}
|
||||
|
||||
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
|
||||
func (w *writerWrapper) WriteHeader(statusCode int) {
|
||||
w.statusCode = statusCode
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
// Metrics is a middleware that collects HTTP server metrics for each endpoint.
|
||||
// It records request duration, status code counts, and request/response body sizes.
|
||||
// If the endpoint is not available in the context, it skips metrics collection.
|
||||
func Metrics(storage *http_metrics.ServerStorage) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
endpoint := http_metrics.ServerEndpoint(r.Context())
|
||||
if endpoint == "" {
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
|
||||
var scSrc scSource
|
||||
buf, isBuffer := w.(*buffer.Buffer)
|
||||
if isBuffer {
|
||||
scSrc = buf
|
||||
} else {
|
||||
scSrc = &writerWrapper{ResponseWriter: w}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
err := next(ctx, w, r)
|
||||
storage.ObserveDuration(r.Method, endpoint, time.Since(start))
|
||||
storage.CountStatusCode(r.Method, endpoint, scSrc.StatusCode())
|
||||
if isBuffer {
|
||||
storage.ObserveRequestBodySize(r.Method, endpoint, len(buf.RequestBody()))
|
||||
storage.ObserveResponseBodySize(r.Method, endpoint, len(buf.ResponseBody()))
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/panic_recovery"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultMaxRequestBodySize is the default maximum allowed request body size (64MB).
|
||||
defaultMaxRequestBodySize = 64 * 1024 * 1024
|
||||
)
|
||||
|
||||
// LogMiddleware is an alias for http.Middleware used for request/response logging.
|
||||
type LogMiddleware http2.Middleware
|
||||
|
||||
// MaxRequestBodySize limits the size of the request body that can be read.
|
||||
// It wraps the request body with http.MaxBytesReader to enforce the limit.
|
||||
func MaxRequestBodySize(maxBytes int64) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery is a middleware that catches panics and converts them to errors.
|
||||
// It ensures the server remains stable even when handler code panics.
|
||||
// Safe for concurrent use.
|
||||
func Recovery() http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {
|
||||
defer panic_recovery.Recover(func(panicErr error) {
|
||||
err = panicErr
|
||||
})
|
||||
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler is a middleware that logs errors and writes appropriate HTTP responses.
|
||||
// It uses the error's logging level and enriches Sentry events with request details.
|
||||
// For HttpError implementations, it writes the error using WriteError; otherwise,
|
||||
// it returns a generic internal service error to hide implementation details.
|
||||
func ErrorHandler(logger log.Logger) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
err := next(ctx, w, r)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
logFunc := logutil.LogLevelFuncForError(err, logger)
|
||||
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Request = sentryRequest(r)
|
||||
})
|
||||
logFunc(logContext, err)
|
||||
|
||||
reqId := requestid.FromContext(ctx)
|
||||
if reqId != "" {
|
||||
w.Header().Set(requestid.Header, reqId)
|
||||
}
|
||||
|
||||
var httpErr HttpError
|
||||
if errors.As(err, &httpErr) {
|
||||
err = httpErr.WriteError(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// hide error details to prevent potential security leaks
|
||||
err = apierrors.NewInternalServiceError(err).WriteError(w)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId is a middleware that manages request IDs for tracing and logging.
|
||||
// It uses the existing request ID from headers if present, or generates a new one.
|
||||
// The request ID is added to the context and response headers.
|
||||
func RequestId() http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
requestId := r.Header.Get(requestid.Header)
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
ctx = requestid.ToContext(ctx, requestId)
|
||||
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
|
||||
|
||||
return next(ctx, w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sentryRequest creates a Sentry request object from an http.Request.
|
||||
// It determines the protocol based on TLS or X-Forwarded-Proto header.
|
||||
func sentryRequest(r *http.Request) *sentry.Request {
|
||||
protocol := "https"
|
||||
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
|
||||
protocol = "http"
|
||||
}
|
||||
url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path)
|
||||
|
||||
return &sentry.Request{
|
||||
URL: url,
|
||||
Method: r.Method,
|
||||
QueryString: r.URL.RawQuery,
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ContextParam creates a ParamMapper that provides context.Context to endpoint functions.
|
||||
// This is automatically included in the default wrapper.
|
||||
func ContextParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "context.Context",
|
||||
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
|
||||
return ctx, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions.
|
||||
// This is automatically included in the default wrapper.
|
||||
func ResponseWriterParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "http.ResponseWriter",
|
||||
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
|
||||
return w, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// RequestParam creates a ParamMapper that provides *http.Request to endpoint functions.
|
||||
// This is automatically included in the default wrapper.
|
||||
func RequestParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "*http.Request",
|
||||
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
|
||||
return r, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
)
|
||||
|
||||
// Wrappable is an interface for types that can be wrapped into an http.HandlerFunc.
|
||||
// Implementations should handle request extraction and response mapping.
|
||||
type Wrappable interface {
|
||||
Wrap(wrapper Wrapper) http2.HandlerFunc
|
||||
}
|
||||
|
||||
// basic is a generic endpoint function type that accepts a request and returns a response.
|
||||
type basic[Req any, Res any] func(ctx context.Context, req Req) (Res, error)
|
||||
|
||||
// New creates a new generic endpoint with request and response types.
|
||||
// The returned endpoint automatically handles JSON body extraction and response mapping.
|
||||
func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res] {
|
||||
return fn
|
||||
}
|
||||
|
||||
// Wrap implements Wrappable for basic endpoints.
|
||||
// It extracts the request body, calls the endpoint function, and maps the response.
|
||||
func (fn basic[Req, Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
req, err := extractBody[Req](ctx, wrapper, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := fn(ctx, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wrapper.BodyMapper.Map(ctx, resp, w)
|
||||
}
|
||||
}
|
||||
|
||||
// withoutResponseBody is an endpoint type that processes a request but returns no response body.
|
||||
type withoutResponseBody[Req any] func(ctx context.Context, req Req) error
|
||||
|
||||
// NewWithoutResponse creates an endpoint that handles a request without returning a response body.
|
||||
// Useful for operations like deletions or fire-and-forget actions.
|
||||
func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req] {
|
||||
return fn
|
||||
}
|
||||
|
||||
// Wrap implements Wrappable for endpoints without response body.
|
||||
func (fn withoutResponseBody[Req]) Wrap(wrapper Wrapper) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
req, err := extractBody[Req](ctx, wrapper, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
// withRequest is an endpoint type that has direct access to the http.Request.
|
||||
type withRequest func(ctx context.Context, r *http.Request) error
|
||||
|
||||
// NewWithRequest creates an endpoint that receives the raw http.Request.
|
||||
// Use this when you need direct access to headers, query parameters, or other request details.
|
||||
func NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest {
|
||||
return fn
|
||||
}
|
||||
|
||||
// Wrap implements Wrappable for withRequest endpoints.
|
||||
func (fn withRequest) Wrap(wrapper Wrapper) http2.HandlerFunc {
|
||||
return func(ctx context.Context, _ http.ResponseWriter, r *http.Request) error {
|
||||
return fn(ctx, r)
|
||||
}
|
||||
}
|
||||
|
||||
// withRequestAndResponse is an endpoint type that has direct access to http.Request and returns a typed response.
|
||||
type withRequestAndResponse[Res any] func(ctx context.Context, r *http.Request) (Res, error)
|
||||
|
||||
// NewWithRequestAndResponse creates an endpoint with direct access to http.Request and automatic response mapping.
|
||||
// Useful when you need direct access to request details while still returning a typed response.
|
||||
func NewWithRequestAndResponse[Res any](fn func(ctx context.Context, r *http.Request) (Res, error)) withRequestAndResponse[Res] {
|
||||
return fn
|
||||
}
|
||||
|
||||
// Wrap implements Wrappable for withRequestAndResponse endpoints.
|
||||
func (fn withRequestAndResponse[Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
resp, err := fn(ctx, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wrapper.BodyMapper.Map(ctx, resp, w)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultHttp is an endpoint type that uses the standard http.HandlerFunc signature.
|
||||
type defaultHttp http2.HandlerFunc
|
||||
|
||||
// NewDefaultHttp creates an endpoint with direct access to ResponseWriter and Request.
|
||||
// This is the most flexible option but bypasses automatic body extraction and mapping.
|
||||
func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp {
|
||||
return fn
|
||||
}
|
||||
|
||||
// Wrap implements Wrappable for defaultHttp endpoints.
|
||||
func (fn defaultHttp) Wrap(wrapper Wrapper) http2.HandlerFunc {
|
||||
return http2.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
// extractBody extracts and unmarshals the request body into the target type.
|
||||
// It uses the wrapper's BodyExtractor to handle the request body.
|
||||
func extractBody[T any](ctx context.Context, w Wrapper, r *http.Request) (T, error) {
|
||||
var req T
|
||||
err := w.BodyExtractor.ExtractV2(ctx, r.Body, &req)
|
||||
if err != nil {
|
||||
return *new(T), err
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// Package endpoint provides a high-level abstraction for building HTTP endpoints
|
||||
// with automatic request/response handling, validation, and middleware support.
|
||||
// It uses Go generics to create type-safe endpoint implementations.
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// HttpError is an interface for errors that can write themselves to an HTTP response.
|
||||
// Implementations should handle their own HTTP status codes and response formatting.
|
||||
type HttpError interface {
|
||||
WriteError(w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
// RequestBodyExtractor is responsible for extracting and unmarshaling request bodies.
|
||||
// It supports both reflection-based and direct pointer-based extraction.
|
||||
type RequestBodyExtractor interface {
|
||||
// Extract extracts the request body into a reflect.Value of the specified type.
|
||||
Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)
|
||||
// ExtractV2 extracts the request body into a pointer directly.
|
||||
ExtractV2(ctx context.Context, reader io.Reader, ptr any) error
|
||||
}
|
||||
|
||||
// ResponseBodyMapper is responsible for marshaling and writing response bodies.
|
||||
type ResponseBodyMapper interface {
|
||||
// Map marshals the result and writes it to the http.ResponseWriter.
|
||||
Map(ctx context.Context, result any, w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
// ParamBuilder is a function that builds a parameter value from the request context.
|
||||
type ParamBuilder func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error)
|
||||
|
||||
// ParamMapper maps a parameter type to its builder function.
|
||||
type ParamMapper struct {
|
||||
// Type is the string representation of the parameter type.
|
||||
Type string
|
||||
// Builder creates the parameter value from the request context.
|
||||
Builder ParamBuilder
|
||||
}
|
||||
|
||||
// Wrapper is the core component for building HTTP endpoints.
|
||||
// It combines parameter mapping, body extraction, response mapping, and middleware support.
|
||||
type Wrapper struct {
|
||||
ParamMappers map[string]ParamMapper
|
||||
BodyExtractor RequestBodyExtractor
|
||||
BodyMapper ResponseBodyMapper
|
||||
Middlewares []http2.Middleware
|
||||
Logger log.Logger
|
||||
}
|
||||
|
||||
// NewWrapper creates a new Wrapper with the specified configuration.
|
||||
// Parameter mappers are stored in a map for efficient type lookup.
|
||||
func NewWrapper(
|
||||
paramMappers []ParamMapper,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
logger log.Logger,
|
||||
) Wrapper {
|
||||
mappers := make(map[string]ParamMapper)
|
||||
for _, mapper := range paramMappers {
|
||||
mappers[mapper.Type] = mapper
|
||||
}
|
||||
return Wrapper{
|
||||
ParamMappers: mappers,
|
||||
BodyExtractor: bodyExtractor,
|
||||
BodyMapper: bodyMapper,
|
||||
Logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint wraps a function as an http.HandlerFunc.
|
||||
//
|
||||
// Use EndpointV2 with New, NewWithoutResponse, NewWithRequest, or NewDefaultHttp instead.
|
||||
// EndpointV2 avoids reflection overhead by using the Wrappable interface.
|
||||
func (m Wrapper) Endpoint(f any) http.HandlerFunc {
|
||||
w, isWrappable := f.(Wrappable)
|
||||
if isWrappable {
|
||||
return m.EndpointV2(w)
|
||||
}
|
||||
|
||||
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
handler := caller.Handle
|
||||
for i := range slices.Backward(m.Middlewares) {
|
||||
handler = m.Middlewares[i](handler)
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
err := handler(r.Context(), w, r)
|
||||
if err != nil {
|
||||
m.Logger.Error(r.Context(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EndpointV2 wraps a Wrappable implementation as an http.HandlerFunc.
|
||||
// It applies middleware in reverse order (last middleware executes first).
|
||||
// This version avoids reflection overhead and is preferred for production use.
|
||||
func (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc {
|
||||
handler := w.Wrap(m)
|
||||
for i := range slices.Backward(m.Middlewares) {
|
||||
handler = m.Middlewares[i](handler)
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
err := handler(r.Context(), w, r)
|
||||
if err != nil {
|
||||
m.Logger.Error(r.Context(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithMiddlewares returns a new Wrapper with additional middleware appended.
|
||||
// The original Wrapper remains unchanged (immutable).
|
||||
func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper {
|
||||
return Wrapper{
|
||||
ParamMappers: m.ParamMappers,
|
||||
BodyExtractor: m.BodyExtractor,
|
||||
BodyMapper: m.BodyMapper,
|
||||
Middlewares: append(m.Middlewares, middlewares...),
|
||||
Logger: m.Logger,
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
# Package `router`
|
||||
|
||||
Пакет `router` предоставляет обертку над [`httprouter`](https://github.com/julienschmidt/httprouter) с поддержкой метрик
|
||||
и удобной регистрацией обработчиков.
|
||||
Интегрируется с системой мониторинга для отслеживания эндпоинтов.
|
||||
|
||||
## Types
|
||||
|
||||
### Router
|
||||
|
||||
Структура для управления HTTP-маршрутами. Обеспечивает регистрацию обработчиков, сбор метрик и работу с параметрами URL.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New() *Router`
|
||||
|
||||
Конструктор роутера.
|
||||
|
||||
#### `(r *Router) GET(path string, handler http.Handler) *Router`
|
||||
|
||||
Зарегистрировать обработчик для GET-запросов. Аналогичные методы: `POST()`, `PUT()`, `DELETE()`.
|
||||
|
||||
#### `(r *Router) Handler(method string, path string, handler http.Handler) *Router`
|
||||
|
||||
Зарегистрировать обработчик для произвольного HTTP-метода.
|
||||
|
||||
#### `(r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)`
|
||||
|
||||
Обработать HTTP-запрос.
|
||||
|
||||
#### `(r *Router) InternalRouter() *httprouter.Router`
|
||||
|
||||
Возвращает внутренний экземпляр `httprouter.Router` для кастомных настроек.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `ParamsFromRequest(http *http.Request) Params`
|
||||
|
||||
Извлечь URL-параметры из запроса.
|
||||
|
||||
#### `ParamsFromContext(ctx context.Context) Params`
|
||||
|
||||
Извлечь URL-параметры из контекста.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := router.New()
|
||||
r.GET("/users/:id", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
params := router.ParamsFromRequest(r)
|
||||
userId := params.ByName("id") /* get id param */
|
||||
log.Println(userId)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
_ = http.ListenAndServe(":8080", r)
|
||||
}
|
||||
|
||||
```
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
// Package router provides HTTP request routing with metrics integration.
|
||||
// It wraps the julienschmidt/httprouter library and adds automatic endpoint metrics collection.
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
)
|
||||
|
||||
// Params is an alias for httprouter.Params, representing URL path parameters.
|
||||
type Params = httprouter.Params
|
||||
|
||||
// Router wraps httprouter.Router with automatic metrics collection for each endpoint.
|
||||
// It supports method-based routing (GET, POST, PUT, DELETE) and fluent API for route configuration.
|
||||
type Router struct {
|
||||
router *httprouter.Router
|
||||
}
|
||||
|
||||
// New creates a new Router instance with a fresh httprouter backend.
|
||||
func New() *Router {
|
||||
return &Router{
|
||||
router: httprouter.New(),
|
||||
}
|
||||
}
|
||||
|
||||
// GET registers an HTTP GET handler for the specified path.
|
||||
// Returns the Router for fluent chaining.
|
||||
func (r *Router) GET(path string, handler http.Handler) *Router {
|
||||
return r.Handler(http.MethodGet, path, handler)
|
||||
}
|
||||
|
||||
// POST registers an HTTP POST handler for the specified path.
|
||||
// Returns the Router for fluent chaining.
|
||||
func (r *Router) POST(path string, handler http.Handler) *Router {
|
||||
return r.Handler(http.MethodPost, path, handler)
|
||||
}
|
||||
|
||||
// PUT registers an HTTP PUT handler for the specified path.
|
||||
// Returns the Router for fluent chaining.
|
||||
func (r *Router) PUT(path string, handler http.Handler) *Router {
|
||||
return r.Handler(http.MethodPut, path, handler)
|
||||
}
|
||||
|
||||
// DELETE registers an HTTP DELETE handler for the specified path.
|
||||
// Returns the Router for fluent chaining.
|
||||
func (r *Router) DELETE(path string, handler http.Handler) *Router {
|
||||
return r.Handler(http.MethodDelete, path, handler)
|
||||
}
|
||||
|
||||
// Handler registers a handler for the specified HTTP method and path.
|
||||
// It automatically wraps the handler with metrics collection.
|
||||
// Returns the Router for fluent chaining.
|
||||
func (r *Router) Handler(method string, path string, handler http.Handler) *Router {
|
||||
r.router.Handler(method, path, r.withMetricEndpoint(method, path, handler))
|
||||
return r
|
||||
}
|
||||
|
||||
// ServeHTTP implements the http.Handler interface and delegates to the underlying httprouter.
|
||||
func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
r.router.ServeHTTP(writer, request)
|
||||
}
|
||||
|
||||
// InternalRouter returns the underlying httprouter instance for advanced configuration.
|
||||
func (r *Router) InternalRouter() *httprouter.Router {
|
||||
return r.router
|
||||
}
|
||||
|
||||
// withMetricEndpoint wraps a handler to add endpoint metrics to the request context.
|
||||
// The endpoint is formatted as "METHOD /path" for metrics identification.
|
||||
func (r *Router) withMetricEndpoint(method string, path string, handler http.Handler) http.Handler {
|
||||
endpoint := fmt.Sprintf("%s %s", method, path)
|
||||
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
ctx := http_metrics.ServerEndpointToContext(request.Context(), endpoint)
|
||||
request = request.WithContext(ctx)
|
||||
handler.ServeHTTP(writer, request)
|
||||
})
|
||||
}
|
||||
|
||||
// ParamsFromRequest extracts URL path parameters from an http.Request.
|
||||
// It retrieves the parameters from the request context.
|
||||
func ParamsFromRequest(http *http.Request) Params {
|
||||
return ParamsFromContext(http.Context())
|
||||
}
|
||||
|
||||
// ParamsFromContext extracts URL path parameters from a context.
|
||||
// It returns empty params if none are present in the context.
|
||||
func ParamsFromContext(ctx context.Context) Params {
|
||||
return httprouter.ParamsFromContext(ctx)
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
// nolint:mnd
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// service is an internal wrapper that delegates to the actual HTTP handler.
|
||||
// It uses atomic.Value for thread-safe handler replacement.
|
||||
type service struct {
|
||||
delegate atomic.Value
|
||||
}
|
||||
|
||||
// ServeHTTP implements the http.Handler interface and delegates to the stored handler.
|
||||
// It returns an internal service error if the handler is not initialized.
|
||||
func (s *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
value, ok := s.delegate.Load().(http.Handler)
|
||||
if !ok {
|
||||
_ = apierrors.NewInternalServiceError(errors.New("handler is not initialized")).
|
||||
WriteError(w)
|
||||
return
|
||||
}
|
||||
|
||||
value.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// ServerOption is a function that configures a Server instance.
|
||||
type ServerOption func(*Server)
|
||||
|
||||
// WithServer allows providing a custom *http.Server for advanced configuration.
|
||||
func WithServer(server *http.Server) ServerOption {
|
||||
return func(srv *Server) {
|
||||
srv.server = server
|
||||
}
|
||||
}
|
||||
|
||||
// Server wraps an http.Server with additional functionality for handler management.
|
||||
// It provides graceful shutdown and handler upgrade capabilities.
|
||||
type Server struct {
|
||||
server *http.Server
|
||||
service *service
|
||||
}
|
||||
|
||||
// NewServer creates a new HTTP server with the specified logger and options.
|
||||
// Default timeouts are set: 3 seconds for ReadHeaderTimeout and 120 seconds for IdleTimeout.
|
||||
// Server is safe for concurrent use.
|
||||
func NewServer(logger log.Logger, opts ...ServerOption) *Server {
|
||||
s := &Server{
|
||||
server: &http.Server{
|
||||
ReadHeaderTimeout: 3 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
ErrorLog: log.StdLoggerWithLevel(
|
||||
logger,
|
||||
log.WarnLevel,
|
||||
log.String("worker", "http server"),
|
||||
),
|
||||
},
|
||||
service: &service{
|
||||
delegate: atomic.Value{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, opts := range opts {
|
||||
opts(s)
|
||||
}
|
||||
|
||||
s.server.Handler = s.service
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the server without interrupting any active connections.
|
||||
// It delegates to the underlying http.Server.Shutdown method.
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
return s.server.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// Upgrade replaces the current HTTP handler with a new one.
|
||||
// This method is safe for concurrent use.
|
||||
func (s *Server) Upgrade(handler http.Handler) {
|
||||
s.service.delegate.Store(handler)
|
||||
}
|
||||
|
||||
// ListenAndServe starts the server on the specified address.
|
||||
// It creates a TCP listener and delegates to Serve.
|
||||
func (s *Server) ListenAndServe(address string) error {
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(context.Background(), "tcp", address)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "listen: %s", address)
|
||||
}
|
||||
|
||||
return s.Serve(listener)
|
||||
}
|
||||
|
||||
// Serve accepts incoming connections on the specified listener and handles requests.
|
||||
// It returns nil when the server is gracefully shut down.
|
||||
func (s *Server) Serve(listener net.Listener) error {
|
||||
err := s.server.Serve(listener)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "serve http")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
# Package `grpc_metrics`
|
||||
|
||||
Пакет `grpc_metrics` предоставляет средства для мониторинга метрик GRPC-клиентов и серверов.
|
||||
|
||||
## Types
|
||||
|
||||
### ClientStorage
|
||||
|
||||
Хранилище метрик GRPC-клиента.
|
||||
|
||||
**Metrics:**
|
||||
|
||||
#### `grpc_client_request_duration_ms{endpoint="..."}`
|
||||
|
||||
Продолжительность вызова внешнего GRPC-сервиса.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewClientStorage(reg *metrics.Registry) *ClientStorage`
|
||||
|
||||
Создаёт и регистрирует метрику `client_request_duration_ms` с лейблом `endpoint` в переданном реестре.
|
||||
|
||||
#### `func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration)`
|
||||
|
||||
Регистрирует длительность GRPC-вызова для заданного `endpoint`.
|
||||
|
||||
### ServerStorage
|
||||
|
||||
Хранилище метрик GRPC-сервера.
|
||||
|
||||
**Metrics:**
|
||||
|
||||
#### `grpc_request_duration_ms{endpoint="..."}`
|
||||
|
||||
Продолжительность обработки входящего GRPC-запроса.
|
||||
|
||||
#### `grpc_request_body_size{endpoint="..."}`
|
||||
|
||||
Размер тела входящего запроса.
|
||||
|
||||
#### `grpc_response_body_size{endpoint="..."}`
|
||||
|
||||
Размер тела ответа.
|
||||
|
||||
#### `grpc_status_code_count{endpoint="...",code="..."}`
|
||||
|
||||
Количество ответов по статус-кодам (`OK`, `InvalidArgument`, и т.д.).
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewServerStorage(reg *metrics.Registry) *ServerStorage`
|
||||
|
||||
Создаёт и регистрирует все метрики сервера с нужными лейблами в переданном реестре.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveDuration(endpoint string, duration time.Duration)`
|
||||
|
||||
Регистрирует длительность обработки GRPC-запроса для `endpoint`.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveRequestBodySize(endpoint string, size int)`
|
||||
|
||||
Регистрирует размер тела запроса в байтах.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveResponseBodySize(endpoint string, size int)`
|
||||
|
||||
Регистрирует размер тела ответа в байтах.
|
||||
|
||||
#### `func (s *ServerStorage) CountStatusCode(endpoint string, code codes.Code)`
|
||||
|
||||
Увеличивает счётчик ответов с соответствующим GRPC-кодом.
|
||||
|
||||
## Prometheus metrics example
|
||||
|
||||
```
|
||||
# HELP grpc_client_request_duration_ms The latencies of calling external services via GRPC
|
||||
# TYPE grpc_client_request_duration_ms summary
|
||||
grpc_client_request_duration_ms{endpoint="UserService.GetUser"} 12.3
|
||||
|
||||
# HELP grpc_request_duration_ms The latency of the GRPC requests
|
||||
# TYPE grpc_request_duration_ms summary
|
||||
grpc_request_duration_ms{endpoint="UserService.GetUser"} 10.5
|
||||
|
||||
# HELP grpc_request_body_size The size of request body
|
||||
# TYPE grpc_request_body_size summary
|
||||
grpc_request_body_size{endpoint="UserService.GetUser"} 512
|
||||
|
||||
# HELP grpc_response_body_size The size of response body
|
||||
# TYPE grpc_response_body_size summary
|
||||
grpc_response_body_size{endpoint="UserService.GetUser"} 1024
|
||||
|
||||
# HELP grpc_status_code_count Counter of statuses codes
|
||||
# TYPE grpc_status_code_count counter
|
||||
grpc_status_code_count{endpoint="UserService.GetUser",code="OK"} 32
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
clientMetrics := grpc_metrics.NewClientStorage(metrics.DefaultRegistry)
|
||||
defer func(start time.Time) {
|
||||
clientMetrics.ObserveDuration("UserService.GetUser", time.Since(start))
|
||||
}(time.Now())
|
||||
|
||||
// ... GRPC call
|
||||
|
||||
serverMetrics := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
serverMetrics.ObserveDuration("UserService.GetUser", 12*time.Millisecond)
|
||||
serverMetrics.ObserveRequestBodySize("UserService.GetUser", 512)
|
||||
serverMetrics.ObserveResponseBodySize("UserService.GetUser", 1024)
|
||||
serverMetrics.CountStatusCode("UserService.GetUser", codes.OK)
|
||||
```
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package grpc_metrics
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
)
|
||||
|
||||
// ClientStorage collects metrics for gRPC client operations, primarily focusing
|
||||
// on request latency when calling external gRPC services.
|
||||
type ClientStorage struct {
|
||||
duration *prometheus.SummaryVec
|
||||
}
|
||||
|
||||
// NewClientStorage creates a new ClientStorage instance and registers its metrics
|
||||
// with the provided registry. Metrics are labeled by the gRPC endpoint.
|
||||
func NewClientStorage(reg *metrics.Registry) *ClientStorage {
|
||||
s := &ClientStorage{
|
||||
duration: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "client_request_duration_ms",
|
||||
Help: "The latencies of calling external services via GRPC",
|
||||
Objectives: metrics.DefaultObjectives,
|
||||
}, []string{"endpoint"})),
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ObserveDuration records the latency of a gRPC client request, labeled by endpoint.
|
||||
func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration) {
|
||||
s.duration.WithLabelValues(endpoint).Observe(metrics.Milliseconds(duration))
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
// Package grpc_metrics provides Prometheus metric collectors for gRPC server and client operations.
|
||||
// It tracks request latencies, body sizes, and status code counts for both incoming gRPC requests
|
||||
// and outgoing gRPC client calls.
|
||||
//
|
||||
// Example usage for gRPC server:
|
||||
//
|
||||
// serverStorage := grpc_metrics.NewServerStorage(reg)
|
||||
// serverStorage.ObserveDuration(endpoint, duration)
|
||||
// serverStorage.CountStatusCode(endpoint, code)
|
||||
//
|
||||
// Example usage for gRPC client:
|
||||
//
|
||||
// clientStorage := grpc_metrics.NewClientStorage(reg)
|
||||
// clientStorage.ObserveDuration(endpoint, duration)
|
||||
package grpc_metrics
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user