/*自定义时间格式*/
type FormatTime int
func (t FormatTime) MarshalJSON() ([]byte, error) {
var tStr string
if t > 0 {
tStr = time.Unix(int64(t),0).Format("2006-01-02 15:04:05") // 设置格式
}
return []byte(fmt.Sprintf(`"%v"`, tStr)), nil
}
type FormatDateTime int
func (t FormatDateTime) MarshalJSON() ([]byte, error) {
var tStr string
if t > 0 {
tStr = time.Unix(int64(t), 0).Format("2006-01-02") // 设置格式
}
return []byte(fmt.Sprintf(`"%v"`, tStr)), nil
}
/*json字符串转json对象*/
type JsonString string
func (s JsonString) MarshalJSON() ([]byte,error) {
return []byte(s),nil
}
type ReqFilteredString string
/*校验sql注入*/
func (s *ReqFilteredString)UnmarshalJSON(b []byte) error {
str := `(,|\')|(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\b(select|update|and|or|delete|insert|trancate|char|chr|into|substr|ascii|declare|exec|count|master|into|drop|execute)\b)`
re, err := regexp.Compile(str)
if err != nil {
return err
}
is_bool := re.MatchString(string(b))
if is_bool{
return errors.New("参数有误")
}
b = bytes.Trim(b, "\"")
*s = ReqFilteredString(b) //此处是重点,UnmarshalJSON重写后,取不到值
return nil
}
golang json重写MarshalJSON和UnmarshalJSON
7 min read