Bladeren bron

Fix ignored fields in ScanStruct

ScanStruct should ignore fields with tag `redis:"-"`. Fix the bug and
add test for the same.

Fix similar bug in redisx package.
Gary Burd 13 jaren geleden
bovenliggende
commit
9c59bb96d4
3 gewijzigde bestanden met toevoegingen van 28 en 14 verwijderingen
  1. 4 1
      redis/scan.go
  2. 20 12
      redis/scan_test.go
  3. 4 1
      redisx/util.go

+ 4 - 1
redis/scan.go

@@ -242,7 +242,10 @@ func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *st
 			fs := &fieldSpec{name: f.Name}
 			fs := &fieldSpec{name: f.Name}
 			tag := f.Tag.Get("redis")
 			tag := f.Tag.Get("redis")
 			p := strings.Split(tag, ",")
 			p := strings.Split(tag, ",")
-			if len(p) > 0 && p[0] != "-" {
+			if len(p) > 0 {
+				if p[0] == "-" {
+					continue
+				}
 				if len(p[0]) > 0 {
 				if len(p[0]) > 0 {
 					fs.name = p[0]
 					fs.name = p[0]
 				}
 				}

+ 20 - 12
redis/scan_test.go

@@ -134,24 +134,32 @@ func ExampleScan() {
 	// Red 5
 	// Red 5
 }
 }
 
 
+type s0 struct {
+	X  int
+	Y  int `redis:"y"`
+	Bt bool
+}
+
+type s1 struct {
+	X  int    `redis:"-"`
+	I  int    `redis:"i"`
+	U  uint   `redis:"u"`
+	S  string `redis:"s"`
+	P  []byte `redis:"p"`
+	B  bool   `redis:"b"`
+	Bt bool
+	Bf bool
+	s0
+}
+
 var scanStructTests = []struct {
 var scanStructTests = []struct {
 	title string
 	title string
 	reply []string
 	reply []string
 	value interface{}
 	value interface{}
 }{
 }{
 	{"basic",
 	{"basic",
-		[]string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "f", "Bt", "1", "Bf", "0"},
-		&struct {
-			I  int    `redis:"i"`
-			U  uint   `redis:"u"`
-			S  string `redis:"s"`
-			P  []byte `redis:"p"`
-			B  bool   `redis:"b"`
-			Bt bool
-			Bf bool
-		}{
-			-1234, 5678, "hello", []byte("world"), false, true, false,
-		},
+		[]string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "t", "Bt", "1", "Bf", "0", "X", "123", "y", "456"},
+		&s1{I: -1234, U: 5678, S: "hello", P: []byte("world"), B: true, Bt: true, Bf: false, s0: s0{X: 123, Y: 456}},
 	},
 	},
 }
 }
 
 

+ 4 - 1
redisx/util.go

@@ -52,7 +52,10 @@ func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *st
 			fs := &fieldSpec{name: f.Name}
 			fs := &fieldSpec{name: f.Name}
 			tag := f.Tag.Get("redis")
 			tag := f.Tag.Get("redis")
 			p := strings.Split(tag, ",")
 			p := strings.Split(tag, ",")
-			if len(p) > 0 && p[0] != "-" {
+			if len(p) > 0 {
+				if p[0] == "-" {
+					continue
+				}
 				if len(p[0]) > 0 {
 				if len(p[0]) > 0 {
 					fs.name = p[0]
 					fs.name = p[0]
 				}
 				}