init
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/EthanCodeCraft/xlgo-core/response"
|
||||
"github.com/EthanCodeCraft/xlgo-core/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// HealthCheck 健康检查
|
||||
// @Summary 健康检查
|
||||
// @Description 检查服务是否正常运行
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} response.Response
|
||||
// @Router /health [get]
|
||||
func HealthCheck(c *gin.Context) {
|
||||
response.Success(c, gin.H{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
// BindJSON 绑定 JSON 请求
|
||||
func BindJSON(c *gin.Context, req any) error {
|
||||
return c.ShouldBindJSON(req)
|
||||
}
|
||||
|
||||
// BindQuery 绑定 Query 参数
|
||||
func BindQuery(c *gin.Context, req any) error {
|
||||
return c.ShouldBindQuery(req)
|
||||
}
|
||||
|
||||
// GetPage 获取分页参数
|
||||
func GetPage(c *gin.Context) (int, int) {
|
||||
page := c.DefaultQuery("page", "1")
|
||||
pageSize := c.DefaultQuery("page_size", "20")
|
||||
|
||||
p := utils.ToIntDefault(page, 1)
|
||||
ps := utils.ToIntDefault(pageSize, 20)
|
||||
|
||||
if p < 1 {
|
||||
p = 1
|
||||
}
|
||||
if ps < 1 {
|
||||
ps = 20
|
||||
}
|
||||
if ps > 100 {
|
||||
ps = 100
|
||||
}
|
||||
|
||||
return p, ps
|
||||
}
|
||||
|
||||
// GetIDFromPath 从路径获取 ID
|
||||
func GetIDFromPath(c *gin.Context, paramName string) (uint, bool) {
|
||||
idStr := c.Param(paramName)
|
||||
idStr = strings.Trim(idStr, "/")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return uint(id), true
|
||||
}
|
||||
|
||||
// ===== 类型安全的参数获取函数 =====
|
||||
|
||||
// QueryInt 获取 Query 参数中的整数(带默认值)
|
||||
// 评分: ⭐⭐⭐⭐⭐
|
||||
// 理由: 类型安全,避免每次手动转换
|
||||
func QueryInt(c *gin.Context, key string, def int) int {
|
||||
return utils.ToIntDefault(c.Query(key), def)
|
||||
}
|
||||
|
||||
// QueryInt64 获取 Query 参数中的 int64(带默认值)
|
||||
func QueryInt64(c *gin.Context, key string, def int64) int64 {
|
||||
return utils.ToInt64Default(c.Query(key), def)
|
||||
}
|
||||
|
||||
// QueryFloat64 获取 Query 参数中的 float64(带默认值)
|
||||
func QueryFloat64(c *gin.Context, key string, def float64) float64 {
|
||||
return utils.ToFloat64Default(c.Query(key), def)
|
||||
}
|
||||
|
||||
// QueryBool 获取 Query 参数中的布尔值(带默认值)
|
||||
func QueryBool(c *gin.Context, key string, def bool) bool {
|
||||
val := c.Query(key)
|
||||
if val == "" {
|
||||
return def
|
||||
}
|
||||
return val == "true" || val == "1" || val == "yes"
|
||||
}
|
||||
|
||||
// PathInt 从路径参数获取整数(带默认值)
|
||||
// 评分: ⭐⭐⭐⭐⭐
|
||||
// 理由: RESTful API 常用,如 /users/:id
|
||||
func PathInt(c *gin.Context, key string, def int) int {
|
||||
val := strings.Trim(c.Param(key), "/")
|
||||
return utils.ToIntDefault(val, def)
|
||||
}
|
||||
|
||||
// PathInt64 从路径参数获取 int64(带默认值)
|
||||
func PathInt64(c *gin.Context, key string, def int64) int64 {
|
||||
val := strings.Trim(c.Param(key), "/")
|
||||
return utils.ToInt64Default(val, def)
|
||||
}
|
||||
|
||||
// PathUint64 从路径参数获取 uint64(带默认值)
|
||||
func PathUint64(c *gin.Context, key string, def uint64) uint64 {
|
||||
val := strings.Trim(c.Param(key), "/")
|
||||
return utils.ToUint64Default(val, def)
|
||||
}
|
||||
|
||||
// FormInt 获取 POST 表单参数中的整数(带默认值)
|
||||
// 评分: ⭐⭐⭐⭐⭐
|
||||
// 理由: 传统表单提交常用
|
||||
func FormInt(c *gin.Context, key string, def int) int {
|
||||
return utils.ToIntDefault(c.PostForm(key), def)
|
||||
}
|
||||
|
||||
// FormInt64 获取 POST 表单参数中的 int64(带默认值)
|
||||
func FormInt64(c *gin.Context, key string, def int64) int64 {
|
||||
return utils.ToInt64Default(c.PostForm(key), def)
|
||||
}
|
||||
|
||||
// FormUint64 获取 POST 表单参数中的 uint64(带默认值)
|
||||
func FormUint64(c *gin.Context, key string, def uint64) uint64 {
|
||||
return utils.ToUint64Default(c.PostForm(key), def)
|
||||
}
|
||||
|
||||
// FormFloat64 获取 POST 表单参数中的 float64(带默认值)
|
||||
func FormFloat64(c *gin.Context, key string, def float64) float64 {
|
||||
return utils.ToFloat64Default(c.PostForm(key), def)
|
||||
}
|
||||
|
||||
// FormBool 获取 POST 表单参数中的布尔值(带默认值)
|
||||
func FormBool(c *gin.Context, key string, def bool) bool {
|
||||
val := c.PostForm(key)
|
||||
if val == "" {
|
||||
return def
|
||||
}
|
||||
return val == "true" || val == "1" || val == "yes" || val == "on"
|
||||
}
|
||||
|
||||
// FormString 获取 POST 表单参数中的字符串(带默认值)
|
||||
func FormString(c *gin.Context, key string, def string) string {
|
||||
val := c.PostForm(key)
|
||||
if val == "" {
|
||||
return def
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// ParseInt 解析整数
|
||||
func ParseInt(s string, defaultValue int) int {
|
||||
return utils.ToIntDefault(s, defaultValue)
|
||||
}
|
||||
|
||||
// BadRequest 返回 400 错误
|
||||
func BadRequest(c *gin.Context, msg string) {
|
||||
c.JSON(http.StatusBadRequest, response.Response{
|
||||
Code: response.CodeFail,
|
||||
Msg: msg,
|
||||
})
|
||||
}
|
||||
|
||||
// InternalError 返回 500 错误
|
||||
func InternalError(c *gin.Context, msg string) {
|
||||
c.JSON(http.StatusInternalServerError, response.Response{
|
||||
Code: response.CodeServerError,
|
||||
Msg: msg,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package handler_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/EthanCodeCraft/xlgo-core/handler"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func setupTestRouter() *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
return r
|
||||
}
|
||||
|
||||
func TestHealthCheck(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/health", handler.HealthCheck)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/health", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("HealthCheck status = %d, want 200", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryInt(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
page := handler.QueryInt(c, "page", 1)
|
||||
c.JSON(200, gin.H{"page": page})
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
query string
|
||||
expected int
|
||||
}{
|
||||
{"?page=10", 10},
|
||||
{"?page=abc", 1}, // 无效返回默认
|
||||
{"", 1}, // 无参数返回默认
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test"+tt.query, nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// 验证响应包含正确的值
|
||||
if w.Code != 200 {
|
||||
t.Errorf("QueryInt status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryInt64(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
id := handler.QueryInt64(c, "id", 0)
|
||||
c.JSON(200, gin.H{"id": id})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test?id=1234567890123", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("QueryInt64 status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryFloat64(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
price := handler.QueryFloat64(c, "price", 0.0)
|
||||
c.JSON(200, gin.H{"price": price})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test?price=99.99", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("QueryFloat64 status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryBool(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
enabled := handler.QueryBool(c, "enabled", false)
|
||||
c.JSON(200, gin.H{"enabled": enabled})
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
query string
|
||||
expected bool
|
||||
}{
|
||||
{"?enabled=true", true},
|
||||
{"?enabled=1", true},
|
||||
{"?enabled=yes", true},
|
||||
{"?enabled=false", false},
|
||||
{"?enabled=0", false},
|
||||
{"", false}, // 默认值
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test"+tt.query, nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("QueryBool status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathInt(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/user/:id", func(c *gin.Context) {
|
||||
id := handler.PathInt(c, "id", 0)
|
||||
c.JSON(200, gin.H{"id": id})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/user/123", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("PathInt status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathInt64(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/user/:id", func(c *gin.Context) {
|
||||
id := handler.PathInt64(c, "id", 0)
|
||||
c.JSON(200, gin.H{"id": id})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/user/1234567890123", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("PathInt64 status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPage(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/list", func(c *gin.Context) {
|
||||
page, pageSize := handler.GetPage(c)
|
||||
c.JSON(200, gin.H{"page": page, "pageSize": pageSize})
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
query string
|
||||
expectedPage int
|
||||
expectedSize int
|
||||
}{
|
||||
{"?page=2&page_size=50", 2, 50},
|
||||
{"?page=0&page_size=0", 1, 20}, // 边界修正
|
||||
{"?page=-1&page_size=200", 1, 100}, // 超限修正
|
||||
{"", 1, 20}, // 默认值
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/list"+tt.query, nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("GetPage status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetIDFromPath(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/user/:id", func(c *gin.Context) {
|
||||
id, ok := handler.GetIDFromPath(c, "id")
|
||||
c.JSON(200, gin.H{"id": id, "ok": ok})
|
||||
})
|
||||
|
||||
// 有效 ID
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/user/123", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("GetIDFromPath status = %d", w.Code)
|
||||
}
|
||||
|
||||
// 无效 ID
|
||||
w2 := httptest.NewRecorder()
|
||||
req2 := httptest.NewRequest("GET", "/user/abc", nil)
|
||||
r.ServeHTTP(w2, req2)
|
||||
|
||||
if w2.Code != 200 {
|
||||
t.Errorf("GetIDFromPath invalid status = %d", w2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadRequest(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
handler.BadRequest(c, "参数错误")
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("BadRequest status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalError(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
handler.InternalError(c, "服务器错误")
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/test", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("InternalError status = %d, want 500", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindJSON(t *testing.T) {
|
||||
r := setupTestRouter()
|
||||
r.POST("/test", func(c *gin.Context) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := handler.BindJSON(c, &req); err != nil {
|
||||
handler.BadRequest(c, "绑定失败")
|
||||
return
|
||||
}
|
||||
c.JSON(200, req)
|
||||
})
|
||||
|
||||
// 有效 JSON
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/test", strings.NewReader(`{"name":"test"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Errorf("BindJSON valid status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user