-
Notifications
You must be signed in to change notification settings - Fork 0
/
escape.go
93 lines (79 loc) · 1.88 KB
/
escape.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package do
import (
"bytes"
"encoding/xml"
"fmt"
"html"
"reflect"
)
// EscapeStruct escape struct field value with escaper, v must be a struct pointer
func EscapeStruct(v any, escaper Escaper) (err error) {
val := reflect.ValueOf(v)
typ := val.Type()
if typ.Kind() != reflect.Pointer {
return fmt.Errorf("v is not a pointer")
}
rval := val.Elem()
rtyp := typ.Elem()
if rtyp.Kind() != reflect.Struct {
return fmt.Errorf("v is not a struct")
}
return escapeStruct(rtyp, rval, escaper)
}
func escapeStruct(rtyp reflect.Type, rval reflect.Value, escaper Escaper) (err error) {
for i := 0; i < rtyp.NumField(); i++ {
fieldTyp := rtyp.Field(i)
fieldVal := rval.Field(i)
if fieldTyp.Anonymous {
if err = escapeStruct(fieldTyp.Type, fieldVal, escaper); err != nil {
return
}
continue
}
if fieldTyp.Type.Kind() == reflect.Slice || fieldTyp.Type.Kind() == reflect.Array {
for j := 0; j < fieldVal.Len(); j++ {
if err = escapeStruct(fieldTyp.Type.Elem(), fieldVal.Index(j), escaper); err != nil {
return
}
}
continue
}
newVal, err := escaper(fieldVal.Interface())
if err != nil {
return fmt.Errorf("escape %+v(%+v) failed", fieldVal, fieldTyp)
}
if newVal != nil {
fieldVal.Set(reflect.ValueOf(newVal))
}
}
return
}
type Escaper func(field any) (any, error)
func XMLEscaper(field any) (r any, err error) {
switch v := field.(type) {
case string:
buf := new(bytes.Buffer)
err = xml.EscapeText(buf, []byte(v))
if err != nil {
return
}
return buf.String(), nil
case []byte:
buf := new(bytes.Buffer)
err = xml.EscapeText(buf, []byte(v))
if err != nil {
return
}
return buf.Bytes(), nil
}
return
}
func HTMLEscaper(field any) (r any, err error) {
switch v := field.(type) {
case string:
return html.EscapeString(v), nil
case []byte:
return StringToBytes(html.EscapeString(BytesToString(v))), nil
}
return
}