参考 Gin 的实现
gin 在 internal/json
包中实现了多个 json 包的序列化能力, 默认使用官方encoding/json
包. 如何保证这些包不会冲突呢?
这里用到了 go build -tags
的能力.
[json.go](https://github.com/gin-gonic/gin/blob/master/internal/json/json.go)
// Copyright 2017 Bo-Yi Wu. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !jsoniter && !go_json && !(sonic && avx && (linux || windows || darwin) && amd64)
// +build !jsoniter
// +build !go_json
// +build !sonic !avx !linux,!windows,!darwin !amd64
package json
import "encoding/json"
var (
// Marshal is exported by gin/json package.
Marshal = json.Marshal
// Unmarshal is exported by gin/json package.
Unmarshal = json.Unmarshal
// MarshalIndent is exported by gin/json package.
MarshalIndent = json.MarshalIndent
// NewDecoder is exported by gin/json package.
NewDecoder = json.NewDecoder
// NewEncoder is exported by gin/json package.
NewEncoder = json.NewEncoder
)
[jsoniter.go](https://github.com/gin-gonic/gin/blob/master/internal/json/jsoniter.go)
// Copyright 2017 Bo-Yi Wu. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build jsoniter
// +build jsoniter
package json
import jsoniter "github.com/json-iterator/go"
var (
json = jsoniter.ConfigCompatibleWithStandardLibrary
// Marshal is exported by gin/json package.
Marshal = json.Marshal
// Unmarshal is exported by gin/json package.
Unmarshal = json.Unmarshal
// MarshalIndent is exported by gin/json package.
MarshalIndent = json.MarshalIndent
// NewDecoder is exported by gin/json package.
NewDecoder = json.NewDecoder
// NewEncoder is exported by gin/json package.
NewEncoder = json.NewEncoder
)
切换 不同的 json实现
采用 jsoniter包
go build -tags=jsoniter .
条件编译
通过在代码中增加注释//+build xxx
时,编译时传递对应的tags值,就会编译不同的文件.
- 构建约束以一行
+build
开始的注释.在+build之后列出了一些条件,在这些条件成立时,该文件应包含在编译的包中; - 约束可以出现在任何源文件中,不限于go文件;
+build
必须出现在package语句之前,+build注释之后应要有一个空行.
参考
-Compile and install the application
-Compile_packages_and_dependencies
-Go条件编译