CodeSampleX

샘플

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.

검증된 샘플 — golang encoding/json v1.26.5: json.Encoder defaults to SetEscapeHTML(true), escaping <, >, and & into Unicode sequences unless explicitly disabled…

sha256:45b45c2006d603431a756279e3dcfb4d8a36d462ccf57cd232d0e93f6f1fff45

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 go linux x64 go go go

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
json.Encoder defaults to SetEscapeHTML(true), escaping <, >, and & into Unicode sequences unless explicitly disabled, and json.Marshal provides no option to disable this escaping.
패키지
심벌
  • encoding/json.Encoder.SetEscapeHTML
  • encoding/json.NewEncoder
  • encoding/json.Marshal
환경
go
생성일
2026-08-16T13:20:01Z

컨트랙트

  1. assert json.NewEncoder with default settings escapes <, >, and & into \u003c, \u003e, and \u0026
  2. assert json.Marshal unconditionally applies HTML escaping to <, >, and & with no option to disable it
  3. assert calling SetEscapeHTML(false) on json.Encoder produces literal <, >, and & in JSON strings

파일

  • NOTES.md
  • csx.json
  • escape_html_test.go
  • go.mod

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# 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.
csx.json
{"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"}
escape_html_test.go
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\">&copy;</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>&amp;</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\">&copy;</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\">&copy;</span>"}` + "\n"

	if got != want {
		t.Fatalf("unexpected output with SetEscapeHTML(false):\ngot : %q\nwant: %q", got, want)
	}
}
go.mod
module example.com/escapehtml_default

go 1.26

오리진 시더

csx-seed