Skip to content

Commit

Permalink
up: Optimized the judgment logic when the type is []byte or string
Browse files Browse the repository at this point in the history
  • Loading branch information
wln32 committed Apr 9, 2024
1 parent e44ece4 commit c90316d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
23 changes: 20 additions & 3 deletions util/gconv/gconv_slice_str.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ func SliceStr(any interface{}) []string {
}

// Strings converts `any` to []string.
// If it is a string or byte slice in JSON array format,
// JSON serialization will be called
func Strings(any interface{}) []string {
if any == nil {
return nil
Expand Down Expand Up @@ -59,24 +61,39 @@ func Strings(any interface{}) []string {
}
case []uint8:
if json.Valid(value) {
_ = json.UnmarshalUseNumber(value, &array)
// Determine whether it is JSON in array format
if value[0] == '[' && value[len(value)-1] == ']' {
_ = json.UnmarshalUseNumber(value, &array)
}
}
// Prevent strings from being null
// See Issue 3465 for details
if array == nil {
array = make([]string, len(value))
for k, v := range value {
array[k] = string(v)
// v = [a-zA-Z]
if v >= 'a' && v <= 'z' || v >= 'A' && v <= 'Z' {
array[k] = string(v)
} else {
array[k] = String(v)
}
}
}

case string:
byteValue := []byte(value)
if json.Valid(byteValue) {
_ = json.UnmarshalUseNumber(byteValue, &array)
// Determine whether it is JSON in array format
if byteValue[0] == '[' && byteValue[len(value)-1] == ']' {
_ = json.UnmarshalUseNumber(byteValue, &array)
}
}
// Prevent strings from being null
// See Issue 3465 for details
if array == nil {
if value == "" {
return []string{}
}
return []string{value}
}
case []uint16:
Expand Down
1 change: 1 addition & 0 deletions util/gconv/gconv_z_unit_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ func Test_Strings(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.AssertEQ(gconv.Strings("null"), []string{"null"})
t.AssertEQ(gconv.Strings([]byte("null")), []string{"n", "u", "l", "l"})
t.AssertEQ(gconv.Strings("{\"name\":\"wln\"}"), []string{"{\"name\":\"wln\"}"})
})
}

Expand Down

0 comments on commit c90316d

Please sign in to comment.