scape html 来自 json post 请求
scape html from json post request in go
我想在请求中转义到 html 一些 json 但它不起作用,解码时出现错误 json
import (
"html/template"
"encoding/json"
"net/http"
"io"
"io/ioutil"
"log"
)
func anyFunction(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
ri, wo := io.Pipe()
go template.HTMLEscape(wo, body)
var t []customStruct
json.NewDecoder(ri).Decode(t) //error: Invalid character:'&' looking for beginning of object key string
...
}
来自客户端的 json 有效,因为我使用 "JSON.stringify(data)"
去 1.9.4
Decode reads the next JSON-encoded value from its input and stores it
in the value pointed to by v.
func (dec *Decoder) Decode(v interface{}) error
错误是由于在您传递值时解码会将地址带到 []customStruct
。在这里更改
func anyFunction(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
ri, wo := io.Pipe()
go template.HTMLEscape(wo, body)
var t []customStruct
json.NewDecoder(ri).Decode(&t)
...
}
不要 html-escape 整个有效的 json 有效负载,您会无意中使其无效,从而导致 json 解码失败。
如果您需要清理 中 有效 json 中包含的值,您可以在首次解组之后执行此操作,或者在解组期间通过实施 json.Unmarshaler
自定义类型上的接口,然后可以清理值的原始字节。
我想在请求中转义到 html 一些 json 但它不起作用,解码时出现错误 json
import (
"html/template"
"encoding/json"
"net/http"
"io"
"io/ioutil"
"log"
)
func anyFunction(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
ri, wo := io.Pipe()
go template.HTMLEscape(wo, body)
var t []customStruct
json.NewDecoder(ri).Decode(t) //error: Invalid character:'&' looking for beginning of object key string
...
}
来自客户端的 json 有效,因为我使用 "JSON.stringify(data)" 去 1.9.4
Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
func (dec *Decoder) Decode(v interface{}) error
错误是由于在您传递值时解码会将地址带到 []customStruct
。在这里更改
func anyFunction(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
ri, wo := io.Pipe()
go template.HTMLEscape(wo, body)
var t []customStruct
json.NewDecoder(ri).Decode(&t)
...
}
不要 html-escape 整个有效的 json 有效负载,您会无意中使其无效,从而导致 json 解码失败。
如果您需要清理 中 有效 json 中包含的值,您可以在首次解组之后执行此操作,或者在解组期间通过实施 json.Unmarshaler
自定义类型上的接口,然后可以清理值的原始字节。