feat: update AIConfig route handler and add validation utility function with tests
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user