错误处理中间件

This commit is contained in:
des
2026-01-15 18:57:32 +08:00
parent 69dad45d6a
commit c61fb947e7
4 changed files with 55 additions and 3 deletions

View File

@@ -0,0 +1,7 @@
package middle
import "github.com/gin-gonic/gin"
func SetContextError(ctx *gin.Context) {
}

View File

@@ -1,6 +1,8 @@
package user package user
import ( import (
"context"
"errors"
"fmt" "fmt"
"net/http" "net/http"
@@ -16,8 +18,8 @@ type Controller struct {
} }
type PostLoginParam struct { type PostLoginParam struct {
account string `binding:"required"` Account string `json:"account" binding:"required"`
password string `binding:"required"` Password string `json:"password" binding:"required"`
} }
func (c *Controller) PostLogin(ctx *gin.Context) { func (c *Controller) PostLogin(ctx *gin.Context) {
@@ -26,6 +28,15 @@ func (c *Controller) PostLogin(ctx *gin.Context) {
fmt.Println("参数解析失败,请确认参数是否为 JSON") fmt.Println("参数解析失败,请确认参数是否为 JSON")
fmt.Println(err) fmt.Println(err)
} }
user, err := gorm.G[User](c.client).Where("account = ?", param.Account).First(context.Background())
if errors.Is(err, gorm.ErrRecordNotFound) {
fmt.Println("没有找到用户")
} else {
fmt.Println("查询错误")
panic(err)
}
fmt.Println("接受参数")
fmt.Println(user)
ctx.JSON(http.StatusOK, gin.H{ ctx.JSON(http.StatusOK, gin.H{
"message": "success", "message": "success",
}) })

View File

@@ -1,6 +1,10 @@
package user_test package user_test
import ( import (
"Crimson-Gatekeeper/internal/common"
"Crimson-Gatekeeper/internal/user"
"bytes"
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -10,11 +14,27 @@ import (
) )
func TestLogin(t *testing.T) { func TestLogin(t *testing.T) {
client, close := common.GetDataBaseClient()
defer close()
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
app := gin.Default() app := gin.Default()
user.New(client).RegisterRoute(app)
w := httptest.NewRecorder() w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/api/v1/user/login", nil) param := gin.H{
"account": "admin",
"password": "123445",
}
data, ero := json.Marshal(param)
if ero != nil {
fmt.Println("序列化失败")
panic(ero)
}
fmt.Println("参数")
fmt.Println(string(data))
req, _ := http.NewRequest("POST", "/api/v1/user/login", bytes.NewReader(data))
app.ServeHTTP(w, req) app.ServeHTTP(w, req)
fmt.Println("测试结果")
fmt.Println(w) fmt.Println(w)
} }

View File

@@ -0,0 +1,14 @@
package user
import (
"time"
)
type User struct {
Id int64
CreateTime time.Time
LastUpdateTime time.Time
Name string
Account string
Passwd string
}