This commit is contained in:
oneao committed 2025-08-13 22:00:31 +08:00
1 parent 01ea998605
commit d1b1aafc57
9 files changed
+82 -35

No files matched your search

@@ -8,6 +8,7 @@ import (
)
func Test(c *router.Context) {
dbClient := db.NewClient(c)
if dbClient == nil {
return
@@ -16,7 +17,7 @@ func Test(c *router.Context) {
sqlStr := "SELECT id, name FROM user"
rows, err := dbClient.QueryRows(sqlStr)
if err != nil {
panic(err)
c.AddError(err)
return
}
@@ -9,7 +9,7 @@ import (
func InitAppRouter() *router.Router {
r := router.NewRouter()
r.Use(middleware.Recover())
r.Use(middleware.Error())
r.Use(middleware.Auth()).ExcludePaths("/auth/login")
r.Use(middleware.Logger())
Whitespace-only changes.
@@ -0,0 +1,24 @@
package middleware
import (
"base-framework/pkg/router"
"base-framework/pkg/utils/response"
"log"
)
// Error 全局业务错误处理中间件
func Error() router.HandlerFunc {
return func(c *router.Context) {
// 执行业务逻辑
c.Next()
// 统一处理错误
if errs := c.Errors(); len(errs) > 0 {
lastErr := errs[len(errs)-1]
log.Printf("[ERROR] %v", lastErr)
response.Error(c).Send()
c.Abort()
}
}
}
@@ -1,18 +0,0 @@
package middleware
import (
"base-framework/pkg/router"
"log"
"runtime/debug"
)
func Recover() router.HandlerFunc {
return func(c *router.Context) {
defer func() {
if err := recover(); err != nil {
log.Printf("[PANIC] %v\n%s", err, debug.Stack())
}
}()
c.Next()
}
}
@@ -38,8 +38,8 @@ func (b *BodyCache) Load(r *http.Request) ([]byte, error) {
// Context 自定义请求上下文
type Context struct {
writer http.ResponseWriter
request *http.Request
Request *http.Request
Writer http.ResponseWriter
params map[string]string
index int
handlers []HandlerFunc
@@ -74,21 +74,21 @@ func (c *Context) Param(key string) string {
// Header 获取请求头
func (c *Context) Header(key string) string {
return c.request.Header.Get(key)
return c.Request.Header.Get(key)
}
// JSON 返回 JSON 格式响应
func (c *Context) JSON(statusCode int, data interface{}) {
c.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
c.writer.WriteHeader(statusCode)
if err := json.NewEncoder(c.writer).Encode(data); err != nil {
http.Error(c.writer, err.Error(), http.StatusInternalServerError)
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
c.Writer.WriteHeader(statusCode)
if err := json.NewEncoder(c.Writer).Encode(data); err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
}
}
// Body 方便读取请求体
func (c *Context) Body() ([]byte, error) {
return c.bodyCache.Load(c.request)
return c.bodyCache.Load(c.Request)
}
// BindJSON 反序列化 JSON 请求体到 obj
@@ -102,10 +102,10 @@ func (c *Context) BindJSON(obj interface{}) error {
// PostForm 获取表单参数
func (c *Context) PostForm(key string) string {
if err := c.request.ParseForm(); err != nil {
if err := c.Request.ParseForm(); err != nil {
return ""
}
return c.request.FormValue(key)
return c.Request.FormValue(key)
}
// Set 存储键值对
@@ -124,3 +124,29 @@ func (c *Context) Get(key string) (interface{}, bool) {
val, ok := c.keys[key]
return val, ok
}
// AddError 只记录错误对象
func (c *Context) AddError(err error) {
if err == nil {
return
}
if c.keys == nil {
c.keys = make(map[string]interface{})
}
if _, exists := c.keys["errors"]; !exists {
c.keys["errors"] = []error{}
}
c.keys["errors"] = append(c.keys["errors"].([]error), err)
}
// Errors 获取所有错误
func (c *Context) Errors() []error {
if c.keys == nil {
return nil
}
if errs, exists := c.keys["errors"]; exists {
return errs.([]error)
}
return nil
}
@@ -209,8 +209,8 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handlers = append(handlers, n.handler)
c := &Context{
writer: w,
request: req,
Writer: w,
Request: req,
params: params,
index: -1,
handlers: handlers,
@@ -3,6 +3,7 @@ package jwt
import (
commonConfig "base-framework/pkg/config"
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt"
@@ -23,6 +24,7 @@ type CustomClaims struct {
// CreateToken 创建一个 JWT token
func CreateToken(orgID, userID string) (string, error) {
expireAt := time.Now().Add(commonConfig.JWT.Expiry)
fmt.Println("Token 过期时间:", expireAt.Format(time.RFC3339))
claims := CustomClaims{
OrgID: orgID,
@@ -5,19 +5,25 @@ import (
"net/http"
)
// 统一响应结构体
type ErrorInfo struct {
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Message string `json:"message,omitempty"`
Stack string `json:"stack,omitempty"`
}
// Result 统一响应结构体
type Result struct {
Code string `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Error *ErrorInfo `json:"error,omitempty"`
}
const (
// 通用
CodeSuccess = "0000" // 成功
CodeFail = "0001" // 失败
// 鉴权 / 登录
CodeNoLogin = "1001" // 未登录
CodeLoginExpired = "1002" // 登录过期
CodeInvalidToken = "1003" // Token 无效
@@ -85,6 +91,12 @@ func (b *Builder) Data(data interface{}) *Builder {
return b
}
// ErrorInfo 设置错误信息
func (b *Builder) ErrorInfo(err *ErrorInfo) *Builder {
b.result.Error = err
return b
}
// Send 发送响应
func (b *Builder) Send() {
if b.result.Data == nil {