Merge branch '1024XEngineer:main' into auth-login
This commit is contained in:
Vendored
+2
@@ -12,12 +12,14 @@ declare module 'vue' {
|
||||
AppSidebar: typeof import('./src/components/Layout/AppSidebar.vue')['default']
|
||||
AuditLogTable: typeof import('./src/components/AuditLogTable.vue')['default']
|
||||
ElButton: typeof import('element-plus/es')['ElButton']
|
||||
ElDivider: typeof import('element-plus/es')['ElDivider']
|
||||
ElForm: typeof import('element-plus/es')['ElForm']
|
||||
ElFormItem: typeof import('element-plus/es')['ElFormItem']
|
||||
ElIcon: typeof import('element-plus/es')['ElIcon']
|
||||
ElInput: typeof import('element-plus/es')['ElInput']
|
||||
ElOption: typeof import('element-plus/es')['ElOption']
|
||||
ElSelect: typeof import('element-plus/es')['ElSelect']
|
||||
ElSpace: typeof import('element-plus/es')['ElSpace']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
SubsystemCard: typeof import('./src/components/SubsystemCard.vue')['default']
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import type { ApiResponse, PaginatedData } from '@/types/api'
|
||||
|
||||
export interface LoginAudit {
|
||||
id: number
|
||||
@@ -39,7 +39,7 @@ const mockOpsAudits: OpsAudit[] = [
|
||||
|
||||
export const auditApi = {
|
||||
// 获取登录审计
|
||||
getLoginAudit(params?: any): Promise<any> {
|
||||
getLoginAudit(_params?: any): Promise<ApiResponse<PaginatedData<LoginAudit>>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
@@ -55,7 +55,7 @@ export const auditApi = {
|
||||
},
|
||||
|
||||
// 获取运维操作审计
|
||||
getOpsAudit(params?: any): Promise<any> {
|
||||
getOpsAudit(_params?: any): Promise<ApiResponse<PaginatedData<OpsAudit>>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
|
||||
export interface LoginRequest {
|
||||
username: string
|
||||
@@ -30,7 +30,7 @@ const mockUser: UserInfo = {
|
||||
|
||||
export const authApi = {
|
||||
// 登录
|
||||
login(data: LoginRequest): Promise<any> {
|
||||
login(_data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
|
||||
// MVP 阶段使用 Mock 数据
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
@@ -48,16 +48,16 @@ export const authApi = {
|
||||
},
|
||||
|
||||
// 登出
|
||||
logout(): Promise<any> {
|
||||
logout(): Promise<ApiResponse<null>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({ code: 0, message: 'success' })
|
||||
resolve({ code: 0, message: 'success', data: null })
|
||||
}, 200)
|
||||
})
|
||||
},
|
||||
|
||||
// 获取用户信息
|
||||
getUserInfo(): Promise<any> {
|
||||
getUserInfo(): Promise<ApiResponse<UserInfo>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import axios from 'axios'
|
||||
import axios, { type AxiosResponse, type AxiosError } from 'axios'
|
||||
import { getToken, removeToken } from '@/utils/auth'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
import { codeMessageMap } from '@/types/api'
|
||||
|
||||
const request = axios.create({
|
||||
baseURL: '/api/v1',
|
||||
@@ -21,22 +23,55 @@ request.interceptors.request.use(
|
||||
}
|
||||
)
|
||||
|
||||
/** HTTP 状态码对应的用户友好提示 */
|
||||
const httpMessageMap: Record<number, string> = {
|
||||
400: '请求参数错误',
|
||||
401: '未授权,请重新登录',
|
||||
403: '没有权限执行此操作',
|
||||
404: '请求的资源不存在',
|
||||
408: '请求超时,请稍后重试',
|
||||
500: '服务器内部错误',
|
||||
502: '网关错误',
|
||||
503: '服务暂时不可用,请稍后重试',
|
||||
}
|
||||
|
||||
/** 根据后端错误码获取用户友好提示 */
|
||||
function getBusinessMessage(code: number, fallback?: string): string {
|
||||
return codeMessageMap[code] || fallback || '请求失败'
|
||||
}
|
||||
|
||||
// 响应拦截器
|
||||
request.interceptors.response.use(
|
||||
(response) => {
|
||||
(response: AxiosResponse<ApiResponse>) => {
|
||||
const { data } = response
|
||||
if (data.code !== 0) {
|
||||
ElMessage.error(data.message || '请求失败')
|
||||
return Promise.reject(new Error(data.message))
|
||||
const message = getBusinessMessage(data.code, data.message)
|
||||
ElMessage.error(message)
|
||||
return Promise.reject(new Error(message))
|
||||
}
|
||||
return data
|
||||
return data as any
|
||||
},
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
(error: AxiosError<ApiResponse>) => {
|
||||
// 优先使用后端返回的错误信息
|
||||
const backendMessage = error.response?.data?.message
|
||||
|
||||
if (error.response) {
|
||||
const status = error.response.status
|
||||
|
||||
if (status === 401) {
|
||||
removeToken()
|
||||
window.location.href = '/login'
|
||||
ElMessage.error(backendMessage || '未授权,请重新登录')
|
||||
} else {
|
||||
const message = backendMessage || httpMessageMap[status] || `请求失败 (${status})`
|
||||
ElMessage.error(message)
|
||||
}
|
||||
ElMessage.error(error.message || '网络错误')
|
||||
} else if (error.code === 'ECONNABORTED') {
|
||||
ElMessage.error('请求超时,请检查网络后重试')
|
||||
} else {
|
||||
ElMessage.error('网络连接异常,请检查网络')
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import request from './request'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
|
||||
export interface Subsystem {
|
||||
id: number
|
||||
@@ -10,6 +10,11 @@ export interface Subsystem {
|
||||
sso_enabled: boolean
|
||||
}
|
||||
|
||||
export interface SSOResponse {
|
||||
sso_url: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
// Mock 数据
|
||||
const mockSubsystems: Subsystem[] = [
|
||||
{
|
||||
@@ -70,7 +75,7 @@ const mockSubsystems: Subsystem[] = [
|
||||
|
||||
export const subsystemApi = {
|
||||
// 获取子系统列表
|
||||
getSubsystems(): Promise<any> {
|
||||
getSubsystems(): Promise<ApiResponse<Subsystem[]>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
@@ -83,7 +88,7 @@ export const subsystemApi = {
|
||||
},
|
||||
|
||||
// 获取 SSO 跳转 URL
|
||||
getSSOUrl(id: number): Promise<any> {
|
||||
getSSOUrl(id: number): Promise<ApiResponse<SSOResponse>> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
const subsystem = mockSubsystems.find((s) => s.id === id)
|
||||
|
||||
@@ -97,7 +97,7 @@ const router = createRouter({
|
||||
})
|
||||
|
||||
// 路由守卫
|
||||
router.beforeEach((to, from, next) => {
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const token = getToken()
|
||||
|
||||
if (to.meta.requiresAuth !== false && !token) {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 后端统一响应格式类型定义
|
||||
* 对应 server/internal/handler/response.go
|
||||
*/
|
||||
|
||||
/** 统一 JSON 响应信封 */
|
||||
export interface ApiResponse<T = any> {
|
||||
/** 业务状态码,0 表示成功 */
|
||||
code: number
|
||||
/** 提示信息 */
|
||||
message: string
|
||||
/** 响应数据 */
|
||||
data: T
|
||||
/** 参数校验错误详情(可选) */
|
||||
details?: Record<string, string[]>
|
||||
}
|
||||
|
||||
/** 分页数据结构 */
|
||||
export interface PaginatedData<T> {
|
||||
total: number
|
||||
items: T[]
|
||||
}
|
||||
|
||||
/** 业务错误码常量,与后端一一对应 */
|
||||
export const ApiCode = {
|
||||
/** 成功 */
|
||||
SUCCESS: 0,
|
||||
/** LDAP 认证失败 */
|
||||
LDAP_AUTH_FAILED: 10001,
|
||||
/** 用户名或密码错误 */
|
||||
INVALID_CREDENTIALS: 10002,
|
||||
/** Token 已过期 */
|
||||
TOKEN_EXPIRED: 10003,
|
||||
/** SSO 未配置 */
|
||||
SSO_NOT_CONFIGURED: 10004,
|
||||
/** SSO 跳转地址生成失败 */
|
||||
SSO_GENERATE_FAILED: 10005,
|
||||
/** 任务创建失败 */
|
||||
TASK_CREATE_FAILED: 20001,
|
||||
/** 任务执行超时 */
|
||||
TASK_EXEC_TIMEOUT: 20002,
|
||||
} as const
|
||||
|
||||
/** 错误码到用户友好提示的映射 */
|
||||
export const codeMessageMap: Record<number, string> = {
|
||||
[ApiCode.LDAP_AUTH_FAILED]: 'LDAP 认证服务异常,请稍后重试',
|
||||
[ApiCode.INVALID_CREDENTIALS]: '用户名或密码错误',
|
||||
[ApiCode.TOKEN_EXPIRED]: '登录已过期,请重新登录',
|
||||
[ApiCode.SSO_NOT_CONFIGURED]: '该子系统未配置 SSO,请联系管理员',
|
||||
[ApiCode.SSO_GENERATE_FAILED]: '生成 SSO 跳转链接失败,请稍后重试',
|
||||
[ApiCode.TASK_CREATE_FAILED]: '创建任务失败,请检查参数后重试',
|
||||
[ApiCode.TASK_EXEC_TIMEOUT]: '任务执行超时,请稍后查看结果',
|
||||
}
|
||||
@@ -33,9 +33,13 @@ const auditData = ref<LoginAudit[]>([])
|
||||
const total = ref(0)
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const { data } = await auditApi.getLoginAudit()
|
||||
auditData.value = data.items
|
||||
total.value = data.total
|
||||
} catch {
|
||||
// 错误已由 request 拦截器统一处理
|
||||
}
|
||||
}
|
||||
|
||||
const refresh = () => {
|
||||
|
||||
@@ -34,9 +34,13 @@ const auditData = ref<OpsAudit[]>([])
|
||||
const total = ref(0)
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const { data } = await auditApi.getOpsAudit()
|
||||
auditData.value = data.items
|
||||
total.value = data.total
|
||||
} catch {
|
||||
// 错误已由 request 拦截器统一处理
|
||||
}
|
||||
}
|
||||
|
||||
const refresh = () => {
|
||||
|
||||
@@ -84,8 +84,8 @@ const handleLogin = async () => {
|
||||
await login(form.username, form.password)
|
||||
ElMessage.success('登录成功')
|
||||
router.push('/')
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '登录失败')
|
||||
} catch {
|
||||
// 错误已由 request 拦截器统一处理
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
@@ -24,8 +24,12 @@ import SubsystemCard from '@/components/SubsystemCard.vue'
|
||||
const subsystems = ref<Subsystem[]>([])
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { data } = await subsystemApi.getSubsystems()
|
||||
subsystems.value = data
|
||||
} catch {
|
||||
// 错误已由 request 拦截器统一处理
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/1024XEngineer/xinfra/server/internal/handler"
|
||||
"github.com/1024XEngineer/xinfra/server/internal/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
// 加载中间件
|
||||
r.Use(middleware.Logger())
|
||||
r.Use(middleware.Recovery())
|
||||
|
||||
// 健康检查
|
||||
r.GET("/api/v1/ping", func(c *gin.Context) {
|
||||
handler.Success(c, gin.H{"time": time.Now().Format(time.RFC3339)})
|
||||
})
|
||||
|
||||
// 测试路由组 — 用于验证统一响应格式
|
||||
testGroup := r.Group("/api/v1/test")
|
||||
{
|
||||
// 成功响应
|
||||
testGroup.GET("/success", func(c *gin.Context) {
|
||||
handler.Success(c, gin.H{
|
||||
"username": "testuser",
|
||||
"role": "admin",
|
||||
})
|
||||
})
|
||||
|
||||
// 业务错误 — 传入错误码
|
||||
// GET /api/v1/test/error/10001 → LDAP 认证失败
|
||||
// GET /api/v1/test/error/10002 → 用户名或密码错误
|
||||
// GET /api/v1/test/error/10003 → Token 已过期
|
||||
// GET /api/v1/test/error/20001 → 任务创建失败
|
||||
// GET /api/v1/test/error/20002 → 任务执行超时
|
||||
testGroup.GET("/error/:code", func(c *gin.Context) {
|
||||
codeStr := c.Param("code")
|
||||
code, err := strconv.Atoi(codeStr)
|
||||
if err != nil {
|
||||
handler.BadRequest(c, "错误码必须是数字")
|
||||
return
|
||||
}
|
||||
details := fmt.Sprintf("这是错误码 %d 的测试响应", code)
|
||||
handler.Error(c, http.StatusOK, code, details)
|
||||
})
|
||||
|
||||
// HTTP 500 错误
|
||||
testGroup.GET("/500", func(c *gin.Context) {
|
||||
handler.InternalError(c, "模拟服务器内部错误")
|
||||
})
|
||||
|
||||
// HTTP 401 未授权
|
||||
testGroup.GET("/401", func(c *gin.Context) {
|
||||
handler.Unauthorized(c, "模拟 Token 过期")
|
||||
})
|
||||
|
||||
// HTTP 403 禁止访问
|
||||
testGroup.GET("/403", func(c *gin.Context) {
|
||||
handler.Forbidden(c, "模拟无权限")
|
||||
})
|
||||
|
||||
// 模拟超时(sleep 超过前端 10s timeout)
|
||||
testGroup.GET("/timeout", func(c *gin.Context) {
|
||||
time.Sleep(15 * time.Second)
|
||||
handler.Success(c, "这条消息不应该出现")
|
||||
})
|
||||
|
||||
// 返回分页数据
|
||||
testGroup.GET("/paginated", func(c *gin.Context) {
|
||||
items := []gin.H{
|
||||
{"id": 1, "name": "item-1"},
|
||||
{"id": 2, "name": "item-2"},
|
||||
{"id": 3, "name": "item-3"},
|
||||
}
|
||||
handler.SuccessWithPaginated(c, 100, items)
|
||||
})
|
||||
}
|
||||
|
||||
fmt.Println("Server starting on :8080...")
|
||||
if err := r.Run(":8080"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
module github.com/1024XEngineer/xinfra/server
|
||||
|
||||
go 1.21
|
||||
|
||||
require github.com/gin-gonic/gin v1.9.1
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/crypto v0.9.0 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/sys v0.8.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
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/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/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
|
||||
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
|
||||
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
|
||||
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
|
||||
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
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=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
@@ -0,0 +1,143 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Response 统一响应结构
|
||||
type Response struct {
|
||||
Code int `json:"code"` // 业务错误码,0 表示成功
|
||||
Message string `json:"message"` // 响应消息
|
||||
Data interface{} `json:"data,omitempty"` // 响应数据,成功时返回
|
||||
Details string `json:"details,omitempty"` // 错误详情,失败时返回
|
||||
}
|
||||
|
||||
// 分页响应结构
|
||||
type PaginatedData struct {
|
||||
Total int64 `json:"total"`
|
||||
Items interface{} `json:"items"`
|
||||
}
|
||||
|
||||
// 业务错误码定义
|
||||
const (
|
||||
// 成功
|
||||
CodeSuccess = 0
|
||||
|
||||
// 认证相关错误 10001-10099
|
||||
CodeLDAPAuthFailed = 10001 // LDAP 认证失败
|
||||
CodeInvalidCredentials = 10002 // 用户名或密码错误
|
||||
CodeTokenExpired = 10003 // Token 已过期
|
||||
CodeSSONotConfigured = 10004 // 子系统未配置 SSO
|
||||
CodeSSOGenerateFailed = 10005 // SSO 跳转生成失败
|
||||
|
||||
// 任务相关错误 20001-20099
|
||||
CodeTaskCreateFailed = 20001 // Ansible 任务创建失败
|
||||
CodeTaskExecTimeout = 20002 // Ansible 任务执行超时
|
||||
)
|
||||
|
||||
// 错误码对应的默认消息
|
||||
var codeMessages = map[int]string{
|
||||
CodeSuccess: "success",
|
||||
CodeLDAPAuthFailed: "LDAP 认证失败",
|
||||
CodeInvalidCredentials: "用户名或密码错误",
|
||||
CodeTokenExpired: "Token 已过期",
|
||||
CodeSSONotConfigured: "子系统未配置 SSO",
|
||||
CodeSSOGenerateFailed: "SSO 跳转生成失败",
|
||||
CodeTaskCreateFailed: "Ansible 任务创建失败",
|
||||
CodeTaskExecTimeout: "Ansible 任务执行超时",
|
||||
}
|
||||
|
||||
// GetMessage 根据错误码获取默认消息
|
||||
func GetMessage(code int) string {
|
||||
if msg, ok := codeMessages[code]; ok {
|
||||
return msg
|
||||
}
|
||||
return "未知错误"
|
||||
}
|
||||
|
||||
// Success 返回成功响应
|
||||
func Success(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Message: GetMessage(CodeSuccess),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// SuccessWithMessage 返回自定义消息的成功响应
|
||||
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Message: message,
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// SuccessWithPaginated 返回分页成功响应
|
||||
func SuccessWithPaginated(c *gin.Context, total int64, items interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: CodeSuccess,
|
||||
Message: GetMessage(CodeSuccess),
|
||||
Data: PaginatedData{
|
||||
Total: total,
|
||||
Items: items,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Error 返回错误响应
|
||||
func Error(c *gin.Context, httpCode int, bizCode int, details string) {
|
||||
c.JSON(httpCode, Response{
|
||||
Code: bizCode,
|
||||
Message: GetMessage(bizCode),
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
|
||||
// ErrorWithMessage 返回自定义消息的错误响应
|
||||
func ErrorWithMessage(c *gin.Context, httpCode int, bizCode int, message string, details string) {
|
||||
c.JSON(httpCode, Response{
|
||||
Code: bizCode,
|
||||
Message: message,
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
|
||||
// BadRequest 返回 400 错误
|
||||
func BadRequest(c *gin.Context, details string) {
|
||||
Error(c, http.StatusBadRequest, CodeInvalidCredentials, details)
|
||||
}
|
||||
|
||||
// Unauthorized 返回 401 错误
|
||||
func Unauthorized(c *gin.Context, details string) {
|
||||
Error(c, http.StatusUnauthorized, CodeTokenExpired, details)
|
||||
}
|
||||
|
||||
// Forbidden 返回 403 错误
|
||||
func Forbidden(c *gin.Context, details string) {
|
||||
c.JSON(http.StatusForbidden, Response{
|
||||
Code: http.StatusForbidden,
|
||||
Message: "无权限访问",
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
|
||||
// NotFound 返回 404 错误
|
||||
func NotFound(c *gin.Context, details string) {
|
||||
c.JSON(http.StatusNotFound, Response{
|
||||
Code: http.StatusNotFound,
|
||||
Message: "资源不存在",
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
|
||||
// InternalError 返回 500 错误
|
||||
func InternalError(c *gin.Context, details string) {
|
||||
c.JSON(http.StatusInternalServerError, Response{
|
||||
Code: http.StatusInternalServerError,
|
||||
Message: "服务器内部错误",
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Logger 返回请求日志中间件
|
||||
// 记录请求方法、路径、状态码、耗时、客户端 IP
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 请求开始时间
|
||||
startTime := time.Now()
|
||||
|
||||
// 处理请求
|
||||
c.Next()
|
||||
|
||||
// 计算耗时
|
||||
duration := time.Since(startTime)
|
||||
|
||||
// 获取请求信息
|
||||
method := c.Request.Method
|
||||
path := c.Request.URL.Path
|
||||
statusCode := c.Writer.Status()
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
// 记录日志
|
||||
log.Printf("[REQUEST] %s %s | %d | %v | %s",
|
||||
method,
|
||||
path,
|
||||
statusCode,
|
||||
duration,
|
||||
clientIP,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/1024XEngineer/xinfra/server/internal/handler"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Recovery 返回 panic 恢复中间件
|
||||
// 捕获请求处理过程中的 panic,返回 500 错误而不是崩溃
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// 记录 panic 堆栈信息
|
||||
log.Printf("[PANIC] %v\n%s", err, debug.Stack())
|
||||
|
||||
// 返回 500 错误
|
||||
handler.InternalError(c, "服务器内部错误")
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user