// Copyright 2026 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. // Package json_test is an external test package on purpose. Each codec // installs API from an init function, and package-level variables of an // in-package test would be initialised before that init runs, leaving API // nil. An importing package is guaranteed to observe a fully initialised // codec/json, so tests here see API exactly as the rest of gin does. package json_test import ( "bytes" "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/gin-gonic/gin/codec/json" ) // TestAPIInstalled guards the build constraints across the codec files. Every // supported combination of tags, toolchain and GOEXPERIMENT must leave exactly // one codec selected; if the constraints ever fail to overlap, no init runs and // API stays nil, which builds cleanly and only panics at the first render. func TestAPIInstalled(t *testing.T) { require.NotNil(t, json.API, "no codec init ran: build constraints do not cover this configuration") assert.NotEmpty(t, json.Package) } type payload struct { Name string `json:"name"` N int `json:"n"` } func TestMarshal(t *testing.T) { got, err := json.API.Marshal(payload{Name: "gin", N: 1}) require.NoError(t, err) assert.JSONEq(t, `{"name":"gin","n":1}`, string(got)) } // TestMarshalEscapesHTML pins the HTML escaping that Context.JSON relies on to // stay safe when a response is embedded in a document. PureJSON is the only // render that opts out, via Encoder.SetEscapeHTML. func TestMarshalEscapesHTML(t *testing.T) { got, err := json.API.Marshal(payload{Name: "