米脂
我想出了自己的解决方案来自己创建函数。希望它对某人有用。func MysqlRealEscapeString(value string) string { replace := map[string]string{"\\":"\\\\", "'":`\'`, "\\0":"\\\\0", "\n":"\\n", "\r":"\\r", `"`:`\"`, "\x1a":"\\Z"} for b, a := range replace { value = strings.Replace(value, b, a, -1) } return value;}1.MysqlRealEscapeString 不对,下面的测试用例会失败func TestEscape(t *testing.T) { mysqlEscapeList := map[string]string{ "\\": "\\\\", "'": `\'`, "\\0": "\\\\0", "\n": "\\n", "\r": "\\r", `"`: `\"`, "\x1a": "\\Z"} for old, want := range mysqlEscapeList { testEscape(t, old, want) } testEscape(t, `<p>123</p><div><img width="1080" />`, `<p>123</p><div><img width=\"1080\" />`)}func testEscape(t *testing.T, origin, want string) { escaped := MysqlRealEscapeString(origin) assert.Equal(t, want, escaped)}改用这个func Escape(sql string) string { dest := make([]byte, 0, 2*len(sql)) var escape byte for i := 0; i < len(sql); i++ { c := sql[i] escape = 0 switch c { case 0: /* Must be escaped for 'mysql' */ escape = '0' break case '\n': /* Must be escaped for logs */ escape = 'n' break case '\r': escape = 'r' break case '\\': escape = '\\' break case '\'': escape = '\'' break case '"': /* Better safe than sorry */ escape = '"' break case '\032': //十进制26,八进制32,十六进制1a, /* This gives problems on Win32 */ escape = 'Z' } if escape != 0 { dest = append(dest, '\\', escape) } else { dest = append(dest, c) } } return string(dest)}