diff --git a/encoding/ghtml/ghtml.go b/encoding/ghtml/ghtml.go index 205b107e7..1064ffd2b 100644 --- a/encoding/ghtml/ghtml.go +++ b/encoding/ghtml/ghtml.go @@ -9,6 +9,7 @@ package ghtml import ( "html" + "reflect" "strings" strip "github.com/grokify/html-strip-tags-go" @@ -57,3 +58,46 @@ func SpecialCharsDecode(s string) string { "'", "'", ).Replace(s) } + +// SpecialCharsMapOrStruct automatically encodes string values/attributes for map/struct. +func SpecialCharsMapOrStruct(mapOrStruct interface{}) error { + var ( + reflectValue = reflect.ValueOf(mapOrStruct) + reflectKind = reflectValue.Kind() + ) + for reflectValue.IsValid() && (reflectKind == reflect.Ptr || reflectKind == reflect.Interface) { + reflectValue = reflectValue.Elem() + reflectKind = reflectValue.Kind() + } + switch reflectKind { + case reflect.Map: + var ( + mapKeys = reflectValue.MapKeys() + mapValue reflect.Value + ) + for _, key := range mapKeys { + mapValue = reflectValue.MapIndex(key) + switch mapValue.Kind() { + case reflect.String: + reflectValue.SetMapIndex(key, reflect.ValueOf(SpecialChars(mapValue.String()))) + case reflect.Interface: + if mapValue.Elem().Kind() == reflect.String { + reflectValue.SetMapIndex(key, reflect.ValueOf(SpecialChars(mapValue.Elem().String()))) + } + } + } + + case reflect.Struct: + var ( + fieldValue reflect.Value + ) + for i := 0; i < reflectValue.NumField(); i++ { + fieldValue = reflectValue.Field(i) + switch fieldValue.Kind() { + case reflect.String: + fieldValue.Set(reflect.ValueOf(SpecialChars(fieldValue.String()))) + } + } + } + return nil +} diff --git a/encoding/ghtml/ghtml_test.go b/encoding/ghtml/ghtml_test.go index 6d215f08f..9752db19b 100644 --- a/encoding/ghtml/ghtml_test.go +++ b/encoding/ghtml/ghtml_test.go @@ -7,13 +7,14 @@ package ghtml_test import ( + "github.com/gogf/gf/frame/g" "testing" "github.com/gogf/gf/encoding/ghtml" "github.com/gogf/gf/test/gtest" ) -func TestStripTags(t *testing.T) { +func Test_StripTags(t *testing.T) { gtest.C(t, func(t *gtest.T) { src := `
Test paragraph.
Other text` dst := `Test paragraph. Other text` @@ -21,7 +22,7 @@ func TestStripTags(t *testing.T) { }) } -func TestEntities(t *testing.T) { +func Test_Entities(t *testing.T) { gtest.C(t, func(t *gtest.T) { src := `A 'quote' "is" bold` dst := `A 'quote' "is" <b>bold</b>` @@ -30,7 +31,7 @@ func TestEntities(t *testing.T) { }) } -func TestSpecialChars(t *testing.T) { +func Test_SpecialChars(t *testing.T) { gtest.C(t, func(t *gtest.T) { src := `A 'quote' "is" bold` dst := `A 'quote' "is" <b>bold</b>` @@ -38,3 +39,43 @@ func TestSpecialChars(t *testing.T) { t.Assert(ghtml.SpecialCharsDecode(dst), src) }) } + +func Test_SpecialCharsMapOrStruct_Map(t *testing.T) { + gtest.C(t, func(t *gtest.T) { + a := g.Map{ + "Title": "