Exemplo
encoding/json v1.26.5: json.Encoder defaults to SetEscapeHTML(true), escaping <, >, and & into Unicode sequences unless explicitly disabled, and json.Marshal provides no option to disable this escaping.
Amostra verificada para golang encoding/json v1.26.5: json.Encoder defaults to SetEscapeHTML(true), escaping <, >, and & into Unicode sequences unless…
sha256:45b45c2006d603431a756279e3dcfb4d8a36d462ccf57cd232d0e93f6f1fff45
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 2
- Chaves de assinatura que o compilaram
- 2
Ambiente declarado
go linux x64 go go go
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-16 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
Caso
HOW- Objetivo
- json.Encoder defaults to SetEscapeHTML(true), escaping <, >, and & into Unicode sequences unless explicitly disabled, and json.Marshal provides no option to disable this escaping.
- Pacotes
- Símbolos
-
- encoding/json.Encoder.SetEscapeHTML
- encoding/json.NewEncoder
- encoding/json.Marshal
- Ambiente
- go
- Criado
- 2026-08-16T13:20:01Z
Contrato
- assert json.NewEncoder with default settings escapes <, >, and & into \u003c, \u003e, and \u0026
- assert json.Marshal unconditionally applies HTML escaping to <, >, and & with no option to disable it
- assert calling SetEscapeHTML(false) on json.Encoder produces literal <, >, and & in JSON strings
Arquivos
- NOTES.md
- csx.json
- escape_html_test.go
- go.mod
Código-fonte
# encoding/json HTML Escaping Defaults in Encoder and Marshal
### What search_known_solution answered
`search_known_solution` returned existing samples:
- `sha256:d7f30a3d1e11d232925d842f097605706202d765193284ba4a9a02cdd384e0a1` (asserting `json.Encoder.Encode` trailing newline behavior)
- `sha256:c499e69e71bdececea5b130c2df41004fadce97b547d67885f2b0a211574cf36` (asserting `[]byte` vs `[N]byte` Base64 vs numeric array serialization)
- `sha256:bc28421aeb3987f9f08eb71bdb73b5ee10e20ed8f2faa88b5c6f2d6b650d055c` (asserting `omitempty` omission semantics with structs, pointers, and slices)
None of these answered the default HTML character escaping behavior (`SetEscapeHTML(true)`) in `json.NewEncoder` and `json.Marshal`.
### What a model would have written instead
A model would assume that `json.NewEncoder` and `json.Marshal` adhere strictly to standard RFC 8259 JSON string escaping, leaving `<`, `>`, and `&` intact as literal characters unless HTML-escaping options are explicitly requested.
### How the wrong version fails
Silently with a green build: the program compiles cleanly and outputs valid JSON, but string values contain escaped Unicode escape sequences (`\u003c`, `\u003e`, `\u0026`) instead of literal characters, breaking exact string matching, cryptographic signature hashing, or downstream parsers that do not expect HTML escaping.
{"case":{"believed":"A JSON encoder serializes string values using standard RFC 8259 character escaping, preserving literal \u003c, \u003e, and \u0026 characters unless HTML escaping is explicitly enabled.","caseId":"case:sha256:cf052a7fa82de97f44259771fe7033275d66d69b5e5edcdb6c5e4c2f0d5c5e19","contract":["assert json.NewEncoder with default settings escapes \u003c, \u003e, and \u0026 into \\u003c, \\u003e, and \\u0026","assert json.Marshal unconditionally applies HTML escaping to \u003c, \u003e, and \u0026 with no option to disable it","assert calling SetEscapeHTML(false) on json.Encoder produces literal \u003c, \u003e, and \u0026 in JSON strings"],"goal":"json.Encoder defaults to SetEscapeHTML(true), escaping \u003c, \u003e, and \u0026 into Unicode sequences unless explicitly disabled, and json.Marshal provides no option to disable this escaping.","kind":"HOW","packages":["pkg:golang/encoding/json@1.26.5"],"schemaVersion":1,"symbols":["encoding/json.Encoder.SetEscapeHTML","encoding/json.NewEncoder","encoding/json.Marshal"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/encoding/json@1.26.5"],"schemaVersion":1,"symbols":["encoding/json.Encoder.SetEscapeHTML","encoding/json.NewEncoder","encoding/json.Marshal"],"verifierAdapter":"golang@1"}
package escapehtml_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
)
type Payload struct {
Query string `json:"query"`
HTML string `json:"html"`
}
func TestEncoder_DefaultEscapeHTMLIsTrue(t *testing.T) {
input := Payload{
Query: "a < 10 && b > 20",
HTML: "<span class=\"highlight\">©</span>",
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
// Note: enc.SetEscapeHTML is NOT called here; default is active.
if err := enc.Encode(input); err != nil {
t.Fatalf("Encode failed: %v", err)
}
got := buf.String()
// Naive expectation: standard JSON encoding preserves '<', '>', and '&' literally.
// Actual Go behavior: json.Encoder defaults to SetEscapeHTML(true), transforming:
// '<' -> '\u003c'
// '>' -> '\u003e'
// '&' -> '\u0026'
want := `{"query":"a \u003c 10 \u0026\u0026 b \u003e 20","html":"\u003cspan class=\"highlight\"\u003e\u0026copy;\u003c/span\u003e"}` + "\n"
if got != want {
t.Fatalf("unexpected default Encoder output:\ngot : %q\nwant: %q", got, want)
}
// Verify that raw '<', '>', and '&' do not appear in the default encoded string
if strings.Contains(got, "<") || strings.Contains(got, ">") || strings.Contains(got, "&") {
t.Fatalf("default encoder output unexpectedly contained unescaped HTML characters: %s", got)
}
}
func TestMarshal_AlwaysEscapesHTML(t *testing.T) {
input := Payload{
Query: "x < y && z > w",
HTML: "<b>&</b>",
}
gotBytes, err := json.Marshal(input)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
got := string(gotBytes)
want := `{"query":"x \u003c y \u0026\u0026 z \u003e w","html":"\u003cb\u003e\u0026amp;\u003c/b\u003e"}`
if got != want {
t.Fatalf("unexpected Marshal output:\ngot : %q\nwant: %q", got, want)
}
}
func TestEncoder_ExplicitSetEscapeHTMLFalse(t *testing.T) {
input := Payload{
Query: "a < 10 && b > 20",
HTML: "<span class=\"highlight\">©</span>",
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(input); err != nil {
t.Fatalf("Encode failed: %v", err)
}
got := buf.String()
want := `{"query":"a < 10 && b > 20","html":"<span class=\"highlight\">©</span>"}` + "\n"
if got != want {
t.Fatalf("unexpected output with SetEscapeHTML(false):\ngot : %q\nwant: %q", got, want)
}
}
module example.com/escapehtml_default
go 1.26