Browse Source

FieldNames

0x4a52466c696e74 1 year ago
parent
commit
a31c1ceed7
2 changed files with 44 additions and 0 deletions
  1. 20 0
      fielder.go
  2. 24 0
      z_test.go

+ 20 - 0
fielder.go

@@ -1,6 +1,7 @@
 package rest
 
 import (
+	"errors"
 	"fmt"
 	"reflect"
 	"strings"
@@ -241,6 +242,25 @@ func Fields(obj any, files RequestFiles, names ...any) (json.Map, IErrorArgs) {
 	return res, nil
 }
 
+// GetStructFields возвращает список полей структуры
+func FieldNames(s any) ([]string, error) {
+	// Получаем тип и проверяем, что это структура
+	t := reflect.TypeOf(s)
+	if t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {
+		return FieldNames(reflect.ValueOf(s).Elem().Interface())
+	} else if t.Kind() != reflect.Struct {
+		return nil, errors.New("expected struct last type")
+	}
+	// Создаем срез для хранения имен полей
+	var fields []string
+	// Перебираем поля структуры
+	for i := 0; i < t.NumField(); i++ {
+		field := t.Field(i)
+		fields = append(fields, camelToSnake(field.Name))
+	}
+	return fields, nil
+}
+
 /////////////////////////////////////////////
 
 func OutFileds(req IRequestIn, obj any, files RequestFiles, names ...any) IRequestOut {

+ 24 - 0
z_test.go

@@ -315,3 +315,27 @@ func TestFieldKeys(t *testing.T) {
 	jm := ObjectFieldKeys(l)
 	jm.LogPretty()
 }
+
+type FieldNamesTest struct {
+	ID       int
+	Name     string
+	ParentID int
+}
+
+func TestFieldNames(t *testing.T) {
+	v := FieldNamesTest{
+		ID:       10,
+		Name:     "Namerrrr",
+		ParentID: 1,
+	}
+
+	var iv any = &v
+
+	fields, err := FieldNames(iv)
+
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	t.Log(fields)
+}