feat: update AIConfig route handler and add validation utility function with tests

This commit is contained in:
mlogclub
2026-05-24 19:57:36 +08:00
parent b1bc1580d9
commit 467759d547
4 changed files with 53 additions and 4 deletions
+19 -1
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"log/slog"
"net/http"
"reflect"
"strconv"
"strings"
"time"
@@ -54,7 +55,7 @@ func ReadForm(ctx *gin.Context, obj any) error {
if err := decoder.Decode(obj, values); err != nil {
return err
}
return validate.Struct(obj)
return validateStruct(obj)
}
func ReadJSON(ctx *gin.Context, obj any) error {
@@ -64,6 +65,23 @@ func ReadJSON(ctx *gin.Context, obj any) error {
if err := ctx.ShouldBindJSON(obj); err != nil {
return err
}
return validateStruct(obj)
}
func validateStruct(obj any) error {
if obj == nil {
return nil
}
value := reflect.ValueOf(obj)
for value.Kind() == reflect.Pointer {
if value.IsNil() {
return validate.Struct(obj)
}
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return nil
}
return validate.Struct(obj)
}
+31
View File
@@ -0,0 +1,31 @@
package params
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func newJSONContext(body string) *gin.Context {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(w)
ctx.Request = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
ctx.Request.Header.Set("Content-Type", "application/json")
return ctx
}
func TestReadJSONAcceptsRootArray(t *testing.T) {
var ids []int64
if err := ReadJSON(newJSONContext(`[3,4]`), &ids); err != nil {
t.Fatalf("ReadJSON returned error: %v", err)
}
if len(ids) != 2 || ids[0] != 3 || ids[1] != 4 {
t.Fatalf("expected ids [3 4], got %#v", ids)
}
}