u
This commit is contained in:
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) {
|
func Test(c *router.Context) {
|
||||||
|
|
||||||
dbClient := db.NewClient(c)
|
dbClient := db.NewClient(c)
|
||||||
if dbClient == nil {
|
if dbClient == nil {
|
||||||
return
|
return
|
||||||
@@ -16,7 +17,7 @@ func Test(c *router.Context) {
|
|||||||
sqlStr := "SELECT id, name FROM user"
|
sqlStr := "SELECT id, name FROM user"
|
||||||
rows, err := dbClient.QueryRows(sqlStr)
|
rows, err := dbClient.QueryRows(sqlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
c.AddError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
func InitAppRouter() *router.Router {
|
func InitAppRouter() *router.Router {
|
||||||
r := router.NewRouter()
|
r := router.NewRouter()
|
||||||
|
|
||||||
r.Use(middleware.Recover())
|
r.Use(middleware.Error())
|
||||||
r.Use(middleware.Auth()).ExcludePaths("/auth/login")
|
r.Use(middleware.Auth()).ExcludePaths("/auth/login")
|
||||||
r.Use(middleware.Logger())
|
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 自定义请求上下文
|
// Context 自定义请求上下文
|
||||||
type Context struct {
|
type Context struct {
|
||||||
writer http.ResponseWriter
|
Request *http.Request
|
||||||
request *http.Request
|
Writer http.ResponseWriter
|
||||||
params map[string]string
|
params map[string]string
|
||||||
index int
|
index int
|
||||||
handlers []HandlerFunc
|
handlers []HandlerFunc
|
||||||
@@ -74,21 +74,21 @@ func (c *Context) Param(key string) string {
|
|||||||
|
|
||||||
// Header 获取请求头
|
// Header 获取请求头
|
||||||
func (c *Context) Header(key string) string {
|
func (c *Context) Header(key string) string {
|
||||||
return c.request.Header.Get(key)
|
return c.Request.Header.Get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// JSON 返回 JSON 格式响应
|
// JSON 返回 JSON 格式响应
|
||||||
func (c *Context) JSON(statusCode int, data interface{}) {
|
func (c *Context) JSON(statusCode int, data interface{}) {
|
||||||
c.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
c.writer.WriteHeader(statusCode)
|
c.Writer.WriteHeader(statusCode)
|
||||||
if err := json.NewEncoder(c.writer).Encode(data); err != nil {
|
if err := json.NewEncoder(c.Writer).Encode(data); err != nil {
|
||||||
http.Error(c.writer, err.Error(), http.StatusInternalServerError)
|
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Body 方便读取请求体
|
// Body 方便读取请求体
|
||||||
func (c *Context) Body() ([]byte, error) {
|
func (c *Context) Body() ([]byte, error) {
|
||||||
return c.bodyCache.Load(c.request)
|
return c.bodyCache.Load(c.Request)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BindJSON 反序列化 JSON 请求体到 obj
|
// BindJSON 反序列化 JSON 请求体到 obj
|
||||||
@@ -102,10 +102,10 @@ func (c *Context) BindJSON(obj interface{}) error {
|
|||||||
|
|
||||||
// PostForm 获取表单参数
|
// PostForm 获取表单参数
|
||||||
func (c *Context) PostForm(key string) string {
|
func (c *Context) PostForm(key string) string {
|
||||||
if err := c.request.ParseForm(); err != nil {
|
if err := c.Request.ParseForm(); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return c.request.FormValue(key)
|
return c.Request.FormValue(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set 存储键值对
|
// Set 存储键值对
|
||||||
@@ -124,3 +124,29 @@ func (c *Context) Get(key string) (interface{}, bool) {
|
|||||||
val, ok := c.keys[key]
|
val, ok := c.keys[key]
|
||||||
return val, ok
|
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)
|
handlers = append(handlers, n.handler)
|
||||||
|
|
||||||
c := &Context{
|
c := &Context{
|
||||||
writer: w,
|
Writer: w,
|
||||||
request: req,
|
Request: req,
|
||||||
params: params,
|
params: params,
|
||||||
index: -1,
|
index: -1,
|
||||||
handlers: handlers,
|
handlers: handlers,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package jwt
|
|||||||
import (
|
import (
|
||||||
commonConfig "base-framework/pkg/config"
|
commonConfig "base-framework/pkg/config"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt"
|
"github.com/golang-jwt/jwt"
|
||||||
@@ -23,6 +24,7 @@ type CustomClaims struct {
|
|||||||
// CreateToken 创建一个 JWT token
|
// CreateToken 创建一个 JWT token
|
||||||
func CreateToken(orgID, userID string) (string, error) {
|
func CreateToken(orgID, userID string) (string, error) {
|
||||||
expireAt := time.Now().Add(commonConfig.JWT.Expiry)
|
expireAt := time.Now().Add(commonConfig.JWT.Expiry)
|
||||||
|
fmt.Println("Token 过期时间:", expireAt.Format(time.RFC3339))
|
||||||
|
|
||||||
claims := CustomClaims{
|
claims := CustomClaims{
|
||||||
OrgID: orgID,
|
OrgID: orgID,
|
||||||
|
|||||||
@@ -5,19 +5,25 @@ import (
|
|||||||
"net/http"
|
"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 {
|
type Result struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Data interface{} `json:"data,omitempty"`
|
Data interface{} `json:"data,omitempty"`
|
||||||
|
Error *ErrorInfo `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// 通用
|
|
||||||
CodeSuccess = "0000" // 成功
|
CodeSuccess = "0000" // 成功
|
||||||
CodeFail = "0001" // 失败
|
CodeFail = "0001" // 失败
|
||||||
|
|
||||||
// 鉴权 / 登录
|
|
||||||
CodeNoLogin = "1001" // 未登录
|
CodeNoLogin = "1001" // 未登录
|
||||||
CodeLoginExpired = "1002" // 登录过期
|
CodeLoginExpired = "1002" // 登录过期
|
||||||
CodeInvalidToken = "1003" // Token 无效
|
CodeInvalidToken = "1003" // Token 无效
|
||||||
@@ -85,6 +91,12 @@ func (b *Builder) Data(data interface{}) *Builder {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ErrorInfo 设置错误信息
|
||||||
|
func (b *Builder) ErrorInfo(err *ErrorInfo) *Builder {
|
||||||
|
b.result.Error = err
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// Send 发送响应
|
// Send 发送响应
|
||||||
func (b *Builder) Send() {
|
func (b *Builder) Send() {
|
||||||
if b.result.Data == nil {
|
if b.result.Data == nil {
|
||||||
|
|||||||
Reference in new issue
Block a user