This commit is contained in:
2026-08-16 20:58:57 +08:00
parent a85477be80
commit a9e1f9e6f8
42 changed files with 1569 additions and 156 deletions
+2 -1
View File
@@ -24,7 +24,7 @@ import (
func NewGinEngine(runtime *conf.Runtime, access *service.AccessControlService, handlers *handler.Set, auth *service.AuthService, security *service.SecurityService, audit *service.AuditRecorder, logger *slog.Logger, version string) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
engine := gin.New()
engine.Use(servermiddleware.RequestMeta(), servermiddleware.Recovery(audit, logger), servermiddleware.AccessLog(runtime, logger, version), servermiddleware.CORS(runtime), servermiddleware.ErrorAudit(audit), servermiddleware.SecurityRateLimit(security))
engine.Use(servermiddleware.RequestMeta(), servermiddleware.Recovery(logger), servermiddleware.AccessLog(runtime, logger, version), servermiddleware.CORS(runtime), servermiddleware.ErrorAudit(logger), servermiddleware.SecurityRateLimit(security))
prefix := ""
config := runtime.Admin()
@@ -60,6 +60,7 @@ func NewGinEngine(runtime *conf.Runtime, access *service.AccessControlService, h
serverrouter.RegisterMedia(private, handlers.Media)
serverrouter.RegisterAnnouncement(private, public, handlers.Announcement)
serverrouter.RegisterEmail(private, handlers.Email)
registerSwagger(engine, prefix, version, logger)
engine.NoRoute(func(c *gin.Context) {
if serveLocalStorage(c, runtime) {
+273 -6
View File
@@ -1,14 +1,22 @@
package server
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"kra/internal/conf"
"kra/internal/server/handler"
)
func TestGinRouteContract(t *testing.T) {
handlers := &handler.Set{
func emptyHandlers() *handler.Set {
return &handler.Set{
Authority: &handler.Authority{}, Menu: &handler.Menu{}, API: &handler.API{},
Permission: &handler.Permission{}, Organization: &handler.Organization{},
Announcement: &handler.Announcement{}, Email: &handler.Email{}, Task: &handler.Task{},
@@ -17,11 +25,12 @@ func TestGinRouteContract(t *testing.T) {
APIToken: &handler.APIToken{}, SystemConfig: &handler.SystemConfig{}, Public: &handler.Public{},
User: &handler.User{}, Navigation: &handler.Navigation{}, Session: &handler.Session{},
}
engine := NewGinEngine(conf.NewRuntime(nil, &conf.AdminBackend{}), nil, handlers, nil, nil, nil, nil, "test")
}
func TestGinRouteContract(t *testing.T) {
engine := NewGinEngine(conf.NewRuntime(nil, &conf.AdminBackend{}), nil, emptyHandlers(), nil, nil, nil, nil, "test")
routes := engine.Routes()
if len(routes) != 177 {
t.Fatalf("route contract changed: got %d routes, want 177", len(routes))
}
actual := make([]string, 0, len(routes))
seen := make(map[string]struct{}, len(routes))
for _, route := range routes {
key := route.Method + " " + route.Path
@@ -29,5 +38,263 @@ func TestGinRouteContract(t *testing.T) {
t.Fatalf("duplicate route %s", key)
}
seen[key] = struct{}{}
actual = append(actual, key)
}
sort.Strings(actual)
if value := strings.Join(actual, "\n"); value != expectedGinRouteContract {
t.Fatalf("route contract changed:\n%s", value)
}
}
func TestGinStartupLogsEveryRegisteredRoute(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
engine := NewGinEngine(conf.NewRuntime(nil, &conf.AdminBackend{}), nil, emptyHandlers(), nil, nil, nil, logger, "test")
text := output.String()
if got, want := strings.Count(text, `"msg":"router registered"`), len(engine.Routes()); got != want {
t.Fatalf("registered route log count = %d, want %d", got, want)
}
if !strings.Contains(text, `"msg":"router register success"`) || !strings.Contains(text, `"route_count":178`) {
t.Fatalf("startup route summary is missing: %s", text)
}
}
func TestSwaggerUsesRegisteredGinRoutes(t *testing.T) {
engine := NewGinEngine(conf.NewRuntime(nil, &conf.AdminBackend{}), nil, emptyHandlers(), nil, nil, nil, nil, "v1.0.0")
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("swagger document status = %d, body=%s", response.Code, response.Body.String())
}
body := response.Body.String()
for _, expected := range []string{`"swagger":"2.0"`, `"version":"v1.0.0"`, `"/base/login"`, `"/timedTask/triggerTimedTask"`, `"/mediaUpload/{uploadId}"`} {
if !strings.Contains(body, expected) {
t.Fatalf("swagger document missing %s", expected)
}
}
}
func TestSwaggerSupportsRouterPrefix(t *testing.T) {
engine := NewGinEngine(conf.NewRuntime(nil, &conf.AdminBackend{RouterPrefix: "/admin"}), nil, emptyHandlers(), nil, nil, nil, nil, "v1.0.0")
for _, path := range []string{"/admin/swagger/index.html", "/admin/swagger/doc.json"} {
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, path, nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("swagger path %s status = %d, body=%s", path, response.Code, response.Body.String())
}
if strings.HasSuffix(path, "/doc.json") && !strings.Contains(response.Body.String(), `"basePath":"/admin"`) {
t.Fatalf("swagger document does not use router prefix: %s", response.Body.String())
}
}
}
func TestLocalStorageResponseHeaders(t *testing.T) {
root := t.TempDir()
for name, body := range map[string]string{"script.html": "<script>alert(1)</script>", "image.png": "png"} {
if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
runtime := conf.NewRuntime(nil, &conf.AdminBackend{Local: &conf.AdminBackend_Local{StorePath: root, PathPrefix: "uploads/file"}, Storage: &conf.AdminBackend_Storage{Type: "local"}})
engine := NewGinEngine(runtime, nil, emptyHandlers(), nil, nil, nil, nil, "test")
for _, test := range []struct {
path string
attachment bool
}{
{path: "/uploads/file/script.html", attachment: true},
{path: "/uploads/file/image.png", attachment: false},
} {
response := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, test.path, nil)
engine.ServeHTTP(response, request)
if response.Code != http.StatusOK || response.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("unexpected static response for %s: status=%d headers=%v", test.path, response.Code, response.Header())
}
hasAttachment := strings.Contains(response.Header().Get("Content-Disposition"), "attachment")
if hasAttachment != test.attachment {
t.Fatalf("attachment header for %s = %v, want %v", test.path, hasAttachment, test.attachment)
}
}
}
const expectedGinRouteContract = `DELETE /api/deleteApisByIds
DELETE /dataAccessLog/deleteDataAccessLogByIds
DELETE /department/deleteDepartment
DELETE /info/deleteInfo
DELETE /info/deleteInfoByIds
DELETE /mediaUpload/:uploadId
DELETE /position/deletePosition
DELETE /sysDictionary/deleteSysDictionary
DELETE /sysDictionaryDetail/deleteSysDictionaryDetail
DELETE /sysError/deleteSysError
DELETE /sysError/deleteSysErrorByIds
DELETE /sysExportTemplate/deleteSysExportTemplate
DELETE /sysExportTemplate/deleteSysExportTemplateByIds
DELETE /sysLoginLog/deleteLoginLog
DELETE /sysLoginLog/deleteLoginLogByIds
DELETE /sysOperationRecord/deleteSysOperationRecord
DELETE /sysOperationRecord/deleteSysOperationRecordByIds
DELETE /sysParams/deleteSysParams
DELETE /sysParams/deleteSysParamsByIds
DELETE /sysVersion/deleteSysVersion
DELETE /sysVersion/deleteSysVersionByIds
DELETE /timedTask/deleteTimedTask
DELETE /user/deleteUser
GET /api/freshCasbin
GET /api/getApiGroups
GET /api/getApiRoles
GET /api/syncApi
GET /attachmentCategory/getCategoryList
GET /authority/getDataScopeDepts
GET /authority/getUsersByAuthority
GET /department/findDepartment
GET /department/getDepartmentUsers
GET /fileUploadAndDownload/findFile
GET /health
GET /info/findInfo
GET /info/getInfoDataSource
GET /info/getInfoList
GET /info/getInfoPublic
GET /logViewer/content
GET /logViewer/dates
GET /logViewer/files
GET /menu/getMenuRoles
GET /position/findPosition
GET /position/getPositionUsers
GET /securityConfig/getSecurityConfig
GET /swagger/*any
GET /sysDictionary/exportSysDictionary
GET /sysDictionary/findSysDictionary
GET /sysDictionary/getSysDictionaryList
GET /sysDictionary/getSysDictionaryListWithDetails
GET /sysDictionaryDetail/findSysDictionaryDetail
GET /sysDictionaryDetail/getDictionaryDetailsByParent
GET /sysDictionaryDetail/getDictionaryPath
GET /sysDictionaryDetail/getDictionaryTreeList
GET /sysDictionaryDetail/getDictionaryTreeListByType
GET /sysDictionaryDetail/getSysDictionaryDetailList
GET /sysError/findSysError
GET /sysError/getSysErrorList
GET /sysExportTemplate/exportExcel
GET /sysExportTemplate/exportExcelByToken
GET /sysExportTemplate/exportTemplate
GET /sysExportTemplate/exportTemplateByToken
GET /sysExportTemplate/findSysExportTemplate
GET /sysExportTemplate/getSysExportTemplateList
GET /sysExportTemplate/previewSQL
GET /sysLoginLog/findLoginLog
GET /sysLoginLog/getLoginLogList
GET /sysOperationRecord/findSysOperationRecord
GET /sysOperationRecord/getSysOperationRecordList
GET /sysParams/findSysParams
GET /sysParams/getSysParam
GET /sysParams/getSysParamsList
GET /sysVersion/downloadVersionJson
GET /sysVersion/findSysVersion
GET /sysVersion/getSysVersionList
GET /timedTask/alertStream
GET /timedTask/getRegisteredMethods
GET /timedTask/getTimedTaskList
GET /timedTask/getTimedTaskLogList
GET /user/getUserInfo
POST /api/createApi
POST /api/deleteApi
POST /api/enterSyncApi
POST /api/getAllApis
POST /api/getApiById
POST /api/getApiList
POST /api/ignoreApi
POST /api/setApiRoles
POST /api/updateApi
POST /attachmentCategory/addCategory
POST /attachmentCategory/deleteCategory
POST /authority/copyAuthority
POST /authority/createAuthority
POST /authority/deleteAuthority
POST /authority/getAuthorityList
POST /authority/setDataScope
POST /authority/setRoleUsers
POST /authorityBtn/canRemoveAuthorityBtn
POST /authorityBtn/getAuthorityBtn
POST /authorityBtn/setAuthorityBtn
POST /base/captcha
POST /base/login
POST /casbin/getPolicyPathByAuthorityId
POST /casbin/updateCasbin
POST /dataAccessLog/getDataAccessLogList
POST /department/createDepartment
POST /department/getDepartmentList
POST /department/setDepartmentUsers
POST /email/emailTest
POST /email/sendEmail
POST /fileUploadAndDownload/deleteFile
POST /fileUploadAndDownload/deleteFiles
POST /fileUploadAndDownload/editFileName
POST /fileUploadAndDownload/getFileList
POST /fileUploadAndDownload/importURL
POST /fileUploadAndDownload/listOssFiles
POST /fileUploadAndDownload/upload
POST /info/createInfo
POST /init/checkdb
POST /init/initdb
POST /jwt/jsonInBlacklist
POST /mediaUpload/chunk
POST /mediaUpload/complete
POST /mediaUpload/init
POST /menu/addBaseMenu
POST /menu/addMenuAuthority
POST /menu/deleteBaseMenu
POST /menu/getBaseMenuById
POST /menu/getBaseMenuTree
POST /menu/getMenu
POST /menu/getMenuAuthority
POST /menu/getMenuList
POST /menu/setMenuRoles
POST /menu/updateBaseMenu
POST /position/createPosition
POST /position/getPositionList
POST /position/setPositionUsers
POST /securityConfig/setSecurityConfig
POST /sysApiToken/createApiToken
POST /sysApiToken/deleteApiToken
POST /sysApiToken/getApiTokenList
POST /sysDictionary/createSysDictionary
POST /sysDictionary/importSysDictionary
POST /sysDictionaryDetail/createSysDictionaryDetail
POST /sysError/createSysError
POST /sysExportTemplate/createSysExportTemplate
POST /sysExportTemplate/importExcel
POST /sysParams/createSysParams
POST /sysVersion/exportVersion
POST /sysVersion/importVersion
POST /system/getServerInfo
POST /system/getSystemConfig
POST /system/reloadSystem
POST /system/setSystemConfig
POST /timedTask/createTimedTask
POST /timedTask/toggleTimedTask
POST /timedTask/triggerTimedTask
POST /user/admin_register
POST /user/changePassword
POST /user/getUserList
POST /user/resetPassword
POST /user/setUserAuthorities
POST /user/setUserAuthority
POST /user/setUserDepartments
POST /user/setUserPositions
PUT /authority/updateAuthority
PUT /department/updateDepartment
PUT /info/updateInfo
PUT /position/updatePosition
PUT /sysDictionary/updateSysDictionary
PUT /sysDictionaryDetail/updateSysDictionaryDetail
PUT /sysError/updateSysError
PUT /sysExportTemplate/updateSysExportTemplate
PUT /sysParams/updateSysParams
PUT /timedTask/updateTimedTask
PUT /user/setSelfInfo
PUT /user/setSelfSetting
PUT /user/setUserInfo`
+1 -1
View File
@@ -160,7 +160,7 @@ func (h *Menu) AuthorityMenus(c *gin.Context) {
}
menus, err := h.service.AuthorityMenus(c.Request.Context(), req.AuthorityID)
if err != nil {
httpx.Fail(c, "获取失败")
httpx.Write(c, httpx.CodeError, gin.H{"menus": menus}, "获取失败")
return
}
httpx.Write(c, httpx.CodeSuccess, gin.H{"menus": menus}, "获取成功")
+13 -1
View File
@@ -67,7 +67,11 @@ func (h *User) Create(c *gin.Context) {
}
result, err := h.service.CreateUserRequest(c.Request.Context(), &req)
if err != nil {
httpx.Fail(c, "注册失败")
if service.IsPasswordPolicyError(err) {
httpx.Fail(c, err.Error())
return
}
httpx.Write(c, httpx.CodeError, gin.H{"user": dto.UserResponse{}}, "注册失败")
return
}
httpx.Write(c, httpx.CodeSuccess, gin.H{"user": result}, "注册成功")
@@ -138,6 +142,10 @@ func (h *User) ResetPassword(c *gin.Context) {
return
}
if err := h.service.ResetPassword(c.Request.Context(), req.ID, req.Password); err != nil {
if service.IsPasswordPolicyError(err) {
httpx.Fail(c, err.Error())
return
}
httpx.Fail(c, "重置失败"+err.Error())
return
}
@@ -164,6 +172,10 @@ func (h *User) ChangePassword(c *gin.Context) {
return
}
if err := h.service.ChangePassword(c.Request.Context(), claims.ID, req.Password, req.NewPassword); err != nil {
if service.IsPasswordPolicyError(err) {
httpx.Fail(c, err.Error())
return
}
httpx.Fail(c, "修改失败,原密码与当前账户不符")
return
}
+28 -8
View File
@@ -3,22 +3,25 @@ package middleware
import (
"bytes"
"encoding/json"
"log/slog"
"strings"
"kra/internal/server/httpx"
"kra/internal/service"
"kra/internal/service/dto"
"github.com/gin-gonic/gin"
)
// ErrorAudit supplies the database sink that the Error-level logging core
// provides. Expected authentication, permission and input failures are not
// system errors and therefore are not inserted into sys_error.
func ErrorAudit(audit *service.AuditRecorder) gin.HandlerFunc {
// ErrorAudit emits a structured Error-level log for unexpected HTTP failures.
// The logging core is the single persistence path for sys_error, matching the
// reference behavior and avoiding duplicate rows for HTTP failures.
func ErrorAudit(logger *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if strings.Contains(c.Request.URL.Path, "/sysError/") || c.Writer.Status() >= 300 && c.Writer.Status() < 500 {
// sysError writes must never audit themselves. Log-viewer failures are
// already recorded by the handler with the underlying filesystem error;
// emitting again from the response envelope would duplicate both the
// classified error file and the sys_error row.
if strings.Contains(c.Request.URL.Path, "/sysError/") || strings.Contains(c.Request.URL.Path, "/logViewer/") || c.Writer.Status() >= 300 && c.Writer.Status() < 500 {
return
}
var response httpx.Response
@@ -32,10 +35,27 @@ func ErrorAudit(audit *service.AuditRecorder) gin.HandlerFunc {
return
}
requestID, _ := c.Get("request_id")
_ = audit.CreateErrorRequest(c.Request.Context(), &dto.ErrorRecordRequest{Form: c.Request.URL.Path, Info: response.Msg, Level: "error", RequestID: stringValue(requestID), TraceID: stringValueFromContext(c, "trace_id")})
if logger != nil {
logger.ErrorContext(c.Request.Context(), "请求处理失败", "mod", failureLogModule(c.Request.URL.Path), "path", c.Request.URL.Path, "method", c.Request.Method, "status", c.Writer.Status(), "error", response.Msg, "request_id", stringValue(requestID), "trace_id", stringValueFromContext(c, "trace_id"))
}
}
}
func failureLogModule(path string) string {
for _, marker := range []string{"/fileUploadAndDownload/", "/mediaUpload/", "/attachmentCategory/"} {
if strings.Contains(path, marker) {
return "upload"
}
}
if strings.Contains(path, "/timedTask/") {
return "timedTask"
}
if strings.Contains(path, "/logViewer/") {
return "log-viewer"
}
return "biz"
}
func expectedClientFailure(message string) bool {
for _, value := range []string{"参数错误", "请输入用户名和密码", "验证码错误", "用户名不存在或者密码错误", "用户被禁止登录", "账号已锁定", "权限不足", "密码已过期", "未登录", "token", "令牌失效"} {
if strings.Contains(message, value) {
@@ -0,0 +1,75 @@
package middleware
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func runErrorAudit(t *testing.T, path, response string, logger *slog.Logger) {
t.Helper()
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(ErrorAudit(logger))
engine.GET(path, func(c *gin.Context) {
c.Set(ctxRespBufferKey, bytes.NewBufferString(response))
c.Set("request_id", "request-1")
c.Set("trace_id", "trace-1")
c.Status(http.StatusOK)
})
request := httptest.NewRequest(http.MethodGet, path, nil)
responseRecorder := httptest.NewRecorder()
engine.ServeHTTP(responseRecorder, request)
}
func TestErrorAuditEmitsUnexpectedBusinessFailure(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
runErrorAudit(t, "/test", `{"code":7,"data":{},"msg":"数据库写入失败"}`, logger)
if text := output.String(); !strings.Contains(text, `"mod":"biz"`) || !strings.Contains(text, `"error":"数据库写入失败"`) {
t.Fatalf("unexpected error log: %s", text)
}
}
func TestErrorAuditUsesFeatureModule(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
runErrorAudit(t, "/timedTask/triggerTimedTask", `{"code":7,"data":{},"msg":"任务执行失败"}`, logger)
if text := output.String(); !strings.Contains(text, `"mod":"timedTask"`) {
t.Fatalf("unexpected feature log module: %s", text)
}
}
func TestErrorAuditSkipsExpectedClientFailure(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
runErrorAudit(t, "/test", `{"code":7,"data":{},"msg":"参数错误"}`, logger)
if output.Len() != 0 {
t.Fatalf("expected no error log, got %s", output.String())
}
}
func TestErrorAuditAllowsNilLogger(t *testing.T) {
runErrorAudit(t, "/test", `{"code":7,"data":{},"msg":"数据库写入失败"}`, nil)
}
func TestErrorAuditSkipsLogViewerFailureAlreadyLoggedByHandler(t *testing.T) {
var output bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&output, nil))
runErrorAudit(t, "/logViewer/content", `{"code":7,"data":{},"msg":"日志文件不可读取"}`, logger)
if output.Len() != 0 {
t.Fatalf("log viewer failure must not be emitted twice, got %s", output.String())
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ func SecurityRateLimit(settings *service.SecurityService) gin.HandlerFunc {
key := "KRA_SecLimit" + c.ClientIP() + c.FullPath()
count, cacheErr := settings.IncrementRateLimit(c.Request.Context(), key, time.Duration(window)*time.Second)
if cacheErr == nil && int(count) > config.LimitCount {
httpx.Fail(c, "请求太过频繁,请稍后再试")
c.JSON(200, gin.H{"code": httpx.CodeError, "msg": "请求太过频繁,请稍后再试"})
c.Abort()
return
}
@@ -0,0 +1,49 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"kra/internal/biz"
"kra/internal/service"
"github.com/gin-gonic/gin"
)
type rateLimitSecurityRepo struct{}
func (rateLimitSecurityRepo) SecurityConfig(context.Context) (*biz.SecurityConfig, error) {
return &biz.SecurityConfig{LimitEnable: true, LimitWindow: 60, LimitCount: 1}, nil
}
func (rateLimitSecurityRepo) SaveSecurityConfig(context.Context, *biz.SecurityConfig) error {
return nil
}
type rateLimitCache struct{}
func (rateLimitCache) Get(context.Context, string) (string, bool, error) { return "", false, nil }
func (rateLimitCache) Set(context.Context, string, string, time.Duration) error { return nil }
func (rateLimitCache) Delete(context.Context, string) error { return nil }
func (rateLimitCache) Increment(context.Context, string, time.Duration) (int64, error) { return 2, nil }
func TestSecurityRateLimitMatchesResponseContract(t *testing.T) {
gin.SetMode(gin.TestMode)
settings := service.NewSecurityService(biz.NewSecurityUsecase(rateLimitSecurityRepo{}, rateLimitCache{}, nil, nil))
engine := gin.New()
engine.Use(SecurityRateLimit(settings))
engine.POST("/base/login", func(c *gin.Context) { c.Status(http.StatusNoContent) })
response := httptest.NewRecorder()
engine.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/base/login", nil))
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", response.Code, response.Body.String())
}
body := response.Body.String()
if !strings.Contains(body, `"code":7`) || !strings.Contains(body, `"msg":"请求太过频繁,请稍后再试"`) || strings.Contains(body, `"data"`) {
t.Fatalf("unexpected rate-limit response: %s", body)
}
}
+2 -9
View File
@@ -1,7 +1,6 @@
package middleware
import (
"fmt"
"log/slog"
"net"
"net/http"
@@ -10,13 +9,10 @@ import (
"runtime/debug"
"strings"
"kra/internal/service"
"kra/internal/service/dto"
"github.com/gin-gonic/gin"
)
func Recovery(audit *service.AuditRecorder, logger *slog.Logger) gin.HandlerFunc {
func Recovery(logger *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
panicValue := recover()
@@ -31,12 +27,9 @@ func Recovery(audit *service.AuditRecorder, logger *slog.Logger) gin.HandlerFunc
}
}
request, _ := httputil.DumpRequest(c.Request, false)
info := fmt.Sprintf("error=%v request=%s stack=%s", panicValue, request, debug.Stack())
if logger != nil {
logger.ErrorContext(c.Request.Context(), "recovery from panic", "mod", "error", "error", panicValue, "request", string(request), "stack", string(debug.Stack()))
logger.ErrorContext(c.Request.Context(), "recovery from panic", "mod", "http", "error", panicValue, "request", string(request), "stack", string(debug.Stack()))
}
requestID, _ := c.Get("request_id")
_ = audit.CreateErrorRequest(c.Request.Context(), &dto.ErrorRecordRequest{Form: c.Request.URL.Path, Info: info, Level: "error", RequestID: stringValue(requestID), TraceID: stringValueFromContext(c, "trace_id")})
if brokenPipe {
if err, ok := panicValue.(error); ok {
_ = c.Error(err)
+167
View File
@@ -0,0 +1,167 @@
package server
import (
"encoding/json"
"log/slog"
"regexp"
"sort"
"strings"
"sync"
"kra/internal/service"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/swag"
)
const swaggerInstanceName = "kra-admin"
var (
swaggerPathParameter = regexp.MustCompile(`:([A-Za-z0-9_]+)`)
swaggerRegistration sync.Once
swaggerDocument runtimeSwaggerDocument
)
type runtimeSwaggerDocument struct {
mu sync.RWMutex
doc string
}
func (d *runtimeSwaggerDocument) ReadDoc() string {
d.mu.RLock()
defer d.mu.RUnlock()
return d.doc
}
func (d *runtimeSwaggerDocument) replace(doc string) {
d.mu.Lock()
d.doc = doc
d.mu.Unlock()
}
func registerSwagger(engine *gin.Engine, prefix, version string, logger *slog.Logger) {
swaggerRegistration.Do(func() { swag.Register(swaggerInstanceName, &swaggerDocument) })
swaggerDocument.replace(buildSwaggerDocument(engine.Routes(), prefix, version))
path := strings.TrimSuffix(prefix, "/") + "/swagger/*any"
engine.GET(path, ginSwagger.WrapHandler(
swaggerFiles.Handler,
ginSwagger.InstanceName(swaggerInstanceName),
ginSwagger.URL("doc.json"),
ginSwagger.PersistAuthorization(true),
))
if logger != nil {
logger.Info("register swagger handler", "mod", "system", "path", path)
}
}
func buildSwaggerDocument(routes []gin.RouteInfo, prefix, version string) string {
basePath := strings.TrimSuffix(prefix, "/")
if basePath == "" {
basePath = "/"
}
sort.Slice(routes, func(i, j int) bool {
if routes[i].Path == routes[j].Path {
return routes[i].Method < routes[j].Method
}
return routes[i].Path < routes[j].Path
})
paths := make(map[string]map[string]any, len(routes))
for _, route := range routes {
method := strings.ToLower(route.Method)
switch method {
case "get", "post", "put", "delete", "patch":
default:
continue
}
apiPath := route.Path
if prefix != "" {
apiPath = strings.TrimPrefix(apiPath, strings.TrimSuffix(prefix, "/"))
}
if apiPath == "" {
apiPath = "/"
}
documentPath := swaggerPathParameter.ReplaceAllString(apiPath, `{$1}`)
group, description := service.RouteMetadata(route.Method, apiPath)
if description == "" {
description = route.Method + " " + apiPath
}
operation := map[string]any{
"tags": []string{group},
"summary": description,
"operationId": swaggerOperationID(route.Method, apiPath),
"produces": []string{"application/json"},
"responses": map[string]any{
"200": map[string]any{"description": "OK", "schema": map[string]any{"$ref": "#/definitions/Response"}},
},
}
if parameters := swaggerPathParameters(apiPath); len(parameters) > 0 {
operation["parameters"] = parameters
}
if !swaggerPublicPath(apiPath) {
operation["security"] = []map[string][]string{{"ApiKeyAuth": {}}}
}
if paths[documentPath] == nil {
paths[documentPath] = map[string]any{}
}
paths[documentPath][method] = operation
}
document := map[string]any{
"swagger": "2.0",
"info": map[string]any{"title": "Kra Administration API", "version": version},
"basePath": basePath,
"schemes": []string{"http", "https"},
"consumes": []string{"application/json"},
"produces": []string{"application/json"},
"securityDefinitions": map[string]any{
"ApiKeyAuth": map[string]any{"type": "apiKey", "name": "x-token", "in": "header"},
},
"paths": paths,
"definitions": map[string]any{
"Response": map[string]any{
"type": "object",
"properties": map[string]any{
"code": map[string]any{"type": "integer"},
"data": map[string]any{"type": "object"},
"msg": map[string]any{"type": "string"},
},
},
},
}
raw, _ := json.Marshal(document)
return string(raw)
}
func swaggerOperationID(method, path string) string {
value := strings.ToLower(method) + "_" + strings.Trim(path, "/")
value = swaggerPathParameter.ReplaceAllString(value, "$1")
return strings.Map(func(r rune) rune {
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' {
return r
}
return '_'
}, value)
}
func swaggerPathParameters(path string) []map[string]any {
matches := swaggerPathParameter.FindAllStringSubmatch(path, -1)
parameters := make([]map[string]any, 0, len(matches))
for _, match := range matches {
parameters = append(parameters, map[string]any{"name": match[1], "in": "path", "required": true, "type": "string"})
}
return parameters
}
func swaggerPublicPath(path string) bool {
for _, marker := range []string{
"/health", "/base/login", "/base/captcha", "/init/checkdb", "/init/initdb",
"/api/freshCasbin", "/sysExportTemplate/exportExcelByToken", "/sysExportTemplate/exportTemplateByToken",
"/sysError/createSysError", "/info/getInfoDataSource", "/info/getInfoPublic",
} {
if path == marker {
return true
}
}
return false
}