I want to scape to html some json in request but it doesn´t work, I get an error when decoding 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
...
}
The json coming from the client it´s valid because I´m using "JSON.stringify(data)" Go 1.9.4
Do not html-escape the whole valid json payload, you are inadvertently invalidating it which causes the json decoding to fail.
If you need to sanitize values contained in the valid json, you can do so either after you first unmarshal it, or during the unmarshaling by implementing the json.Unmarshaler
interface on a custom type which could then sanitize the raw bytes of the value.
According to GoLang json package
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
The error is due to decode will take the address to []customStruct
while you are passing the value. Change here
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)
...
}