mirror of
https://github.com/gin-gonic/gin.git
synced 2026-04-29 23:23:18 +08:00
2.6 KiB
2.6 KiB
Feature: JSON-Iterator Integration Example & Test Fixes
Description
This PR addresses issue #2810 by providing a complete, working example of how to integrate json-iterator/go with Gin. Additionally, it includes critical fixes for existing tests that were failing or behaving inconsistently when the -tags=jsoniter build tag was active.
Changes
1. New Example
- Location:
examples/json-iterator - Content: Added a
json_iterator_test.goto the existing example. This allows developers to verify the integration in isolation without running the entire suite. - Goal: Demonstrates how to replace the default
encoding/jsonbinding withjson-iteratorfor performance improvements.
2. Critical Test Fixes
Running go test -tags=jsoniter ./... previously caused failures. The following fixes ensure full compatibility:
-
gin_integration_test.go:- Issue:
TestRunEmptyrelied on the default port:8080. When running tests in parallel or on CI/CD (like GitHub Actions), this often resulted inbind: address already in useerrors. - Fix: The test now dynamically allocates a random available port (using
:0), eliminating port conflicts.
- Issue:
-
binding/binding_test.go:- Issue:
TestUriBindingfailed becausejson-iteratorbehaves slightly differently thanencoding/jsonon error. Specifically,json-iteratormay allocate an empty map before returning an error, whereas the standard library leaves it asnil. - Fix: Relaxed the assertion to accept either
nilor an empty map when an error occurs, preserving correctness for both engines.
- Issue:
-
context_test.go:- Issue:
TestContextBindRequestTooLargeexpected a413 Request Entity Too Largestatus code. However, the underlyingjson-iteratorlibrary returns a400 Bad Requestwhen the body size limit is exceeded. - Fix: Updated the test to explicitly accept
400 Bad Requestwhen thejsoniterbuild tag is active, matching the library's actual behavior.
- Issue:
How to Verify
Run the Example
go run -tags=jsoniter examples/json-iterator/main.go
# Expected Output: Server starts on :8080
Run All Tests (with json-iterator)
go test -v -tags=jsoniter ./...
# Expected Output: All tests pass (ok)
Run Standard Tests (Regression Check)
go test -v ./...
# Expected Output: All tests pass (ok)
Checklist
- Open pull request against the
masterbranch. - All tests pass locally with
-tags=jsoniter. - Standard tests pass (no regressions).
- Documentation/Examples added.
Fixes #2810