func main() { src, _ := json.Marshal(&Message{"annnnn", "extt<tt>"}) var b bytes.Buffer //json.Compact(&b, src) json.HTMLEscape(&b, src) b.WriteTo(os.Stdout) }
// ServeHTTP shows the current plans in the query cache. func (plr *Planner) ServeHTTP(response http.ResponseWriter, request *http.Request) { if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil { acl.SendError(response, err) return } if request.URL.Path == "/debug/query_plans" { keys := plr.plans.Keys() response.Header().Set("Content-Type", "text/plain") response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys)))) for _, v := range keys { response.Write([]byte(fmt.Sprintf("%#v\n", v))) if plan, ok := plr.plans.Peek(v); ok { if b, err := json.MarshalIndent(plan, "", " "); err != nil { response.Write([]byte(err.Error())) } else { response.Write(b) } response.Write(([]byte)("\n\n")) } } } else if request.URL.Path == "/debug/vschema" { response.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.MarshalIndent(plr.VSchema().Keyspaces, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) } else { response.WriteHeader(http.StatusNotFound) } }
func thJsonify(v interface{}) html.JS { bs, err := json.Marshal(v) assert(err) buf := new(bytes.Buffer) json.HTMLEscape(buf, bs) return html.JS(buf.String()) }
func TestHTMLEscape(t *testing.T) { var b, want bytes.Buffer m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) json.HTMLEscape(&b, []byte(m)) if !bytes.Equal(b.Bytes(), want.Bytes()) { t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) } }
func (w *JsonWriter) WriteStr(name, val string) *JsonWriter { w.checkSeperator() val = strings.Replace(val, "\"", "\\\"", -1) w.writeIdent(name) w.buffer.WriteByte('"') json.HTMLEscape(&w.buffer, []byte(val)) w.buffer.WriteByte('"') return w }
func main() { dst := new(bytes.Buffer) src := []byte(`{ "Name":"tony.shao", "Age":25, "Job":"Programmer<Escaping>" }`) json.HTMLEscape(dst, src) fmt.Println(dst) }
func NewEncoder(opts ...Options) martini.Handler { return func(c martini.Context, w http.ResponseWriter) { wrappedWriter := newWrappedResponseWriter(w) c.MapTo(wrappedWriter, (*http.ResponseWriter)(nil)) c.MapTo(encoder.JsonEncoder{PrettyPrint: true}, (*encoder.Encoder)(nil)) var rtnHandler martini.ReturnHandler rtnHandler = func(ctx martini.Context, vals []reflect.Value) { rv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) res := rv.Interface().(http.ResponseWriter) var responseVal reflect.Value if len(vals) > 1 && vals[0].Kind() == reflect.Int { res.WriteHeader(int(vals[0].Int())) responseVal = vals[1] } else if len(vals) > 0 { responseVal = vals[0] } if isNil(responseVal) { wrappedRes := res.(*wrappedResponseWriter) code := wrappedRes.statusCode if code == 0 { panic(errors.New("No return code set for error")) } responseVal = reflect.ValueOf(errorResponse{Error: code, Message: http.StatusText(code)}) } if canDeref(responseVal) { responseVal = responseVal.Elem() } if isByteSlice(responseVal) { res.Write(responseVal.Bytes()) } else if isStruct(responseVal) || isStructSlice(responseVal) { encv := ctx.Get(inject.InterfaceOf((*encoder.Encoder)(nil))) enc := encv.Interface().(encoder.Encoder) res.Header().Set("Content-Type", "application/json; charset=utf-8") buf := bytes.NewBuffer(encoder.Must(enc.Encode(responseVal.Interface()))) if len(opts) > 0 { if opts[0].Html { val := buf.Bytes() buf.Reset() json.HTMLEscape(buf, val) } if opts[0].Indent { val := buf.Bytes() buf.Reset() json.Indent(buf, val, "", "\t") } } res.Write(buf.Bytes()) } else { res.Write([]byte(responseVal.String())) } } c.Map(rtnHandler) } }
func (si *SchemaInfo) handleHTTPQueryRules(response http.ResponseWriter, request *http.Request) { response.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.MarshalIndent(si.queryRuleSources, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) }
// WriteJSON is specified on the Context interface. func (ctx *context) WriteJSON(data interface{}, html bool) { body, err := json.Marshal(data) if err != nil { http.Error(ctx.responseWriter, err.Error(), http.StatusInternalServerError) } if html { var buf bytes.Buffer json.HTMLEscape(&buf, body) body = buf.Bytes() } ctx.responseWriter.Header().Set("Content-Type", ContentTypeJSON) ctx.responseWriter.Write(body) }
// MarshalJSON implements the json.Marshaler interface. func (n *NullString) MarshalJSON() ([]byte, error) { if !n.Valid { return nullString, nil } body, err := json.Marshal(n.String) if err != nil { return nil, err } if escapeHTML { var buf bytes.Buffer json.HTMLEscape(&buf, body) return buf.Bytes(), nil } else { return body, nil } }
func JsonMarshal(th InterpreterThread, obj RObject, includePrivate bool) (encoded string, err error) { visited := make(map[RObject]bool) tree, err := obj.ToMapListTree(th, includePrivate, visited) if err != nil { return } b, err := json.Marshal(tree) if err != nil { return } var buf bytes.Buffer json.HTMLEscape(&buf, b) encoded = buf.String() return }
func main() { pa := &Address{"private", "Aartselaar", "Belgium"} wa := &Address{"work", "Boom", "Belgium"} vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"} fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none // JSON format: js, _ := json.Marshal(vc) jsEscaped := new(bytes.Buffer) json.HTMLEscape(jsEscaped, js) //fa escape di caratter per essere messo nei tag <script> fmt.Printf("JSON format: %s\n", js) file, err := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0) if err != nil { log.Fatal(err) } defer file.Close() enc := json.NewEncoder(file) errE := enc.Encode(vc) if errE != nil { log.Fatal(errE) } }
func (self *Builder) Value(value interface{}) *Builder { if value == nil { self.buffer.WriteString("null") } else if writer, ok := value.(Writer); ok { writer.WriteJSON(self) } else { v := reflect.ValueOf(value) switch v.Kind() { case reflect.String: self.buffer.WriteByte('"') json.HTMLEscape(&self.buffer, []byte(v.String())) self.buffer.WriteByte('"') case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: self.buffer.WriteString(strconv.FormatInt(v.Int(), 10)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: self.buffer.WriteString(strconv.FormatUint(v.Uint(), 10)) case reflect.Float32, reflect.Float64: self.buffer.WriteString(strconv.FormatFloat(v.Float(), 'f', -1, 64)) case reflect.Bool: if v.Bool() { self.buffer.WriteString("true") } else { self.buffer.WriteString("false") } default: panic("Type not supported as JSON value") } } self.buffer.WriteByte(',') self.afterName = false return self }
func (si *SchemaInfo) ServeHTTP(response http.ResponseWriter, request *http.Request) { if request.URL.Path == "/debug/query_plans" { keys := si.queries.Keys() response.Header().Set("Content-Type", "text/plain") response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys)))) for _, v := range keys { response.Write([]byte(fmt.Sprintf("%#v\n", v))) if plan := si.getQuery(v); plan != nil { if b, err := json.MarshalIndent(plan.ExecPlan, "", " "); err != nil { response.Write([]byte(err.Error())) } else { response.Write(b) } response.Write(([]byte)("\n\n")) } } } else if request.URL.Path == "/debug/query_stats" { keys := si.queries.Keys() response.Header().Set("Content-Type", "application/json; charset=utf-8") qstats := make([]perQueryStats, 0, len(keys)) for _, v := range keys { if plan := si.getQuery(v); plan != nil { var pqstats perQueryStats pqstats.Query = unicoded(plan.DisplayQuery) pqstats.Table = plan.TableName pqstats.Plan = plan.PlanId pqstats.QueryCount, pqstats.Time, pqstats.RowCount, pqstats.ErrorCount = plan.Stats() qstats = append(qstats, pqstats) } } if b, err := json.MarshalIndent(qstats, "", " "); err != nil { response.Write([]byte(err.Error())) } else { response.Write(b) } } else if request.URL.Path == "/debug/table_stats" { response.Header().Set("Content-Type", "application/json; charset=utf-8") si.mu.Lock() tstats := make(map[string]struct{ hits, absent, misses, invalidations int64 }) var temp, totals struct{ hits, absent, misses, invalidations int64 } for k, v := range si.tables { if v.CacheType != schema.CACHE_NONE { temp.hits, temp.absent, temp.misses, temp.invalidations = v.Stats() tstats[k] = temp totals.hits += temp.hits totals.absent += temp.absent totals.misses += temp.misses totals.invalidations += temp.invalidations } } si.mu.Unlock() response.Write([]byte("{\n")) for k, v := range tstats { fmt.Fprintf(response, "\"%s\": {\"Hits\": %v, \"Absent\": %v, \"Misses\": %v, \"Invalidations\": %v},\n", k, v.hits, v.absent, v.misses, v.invalidations) } fmt.Fprintf(response, "\"Totals\": {\"Hits\": %v, \"Absent\": %v, \"Misses\": %v, \"Invalidations\": %v}\n", totals.hits, totals.absent, totals.misses, totals.invalidations) response.Write([]byte("}\n")) } else if request.URL.Path == "/debug/schema" { response.Header().Set("Content-Type", "application/json; charset=utf-8") tables := si.GetSchema() b, err := json.MarshalIndent(tables, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) } else { response.WriteHeader(http.StatusNotFound) } }