gin通过go build -tags实现json包切换及库分析
作者:Memory
这篇文章主要为大家介绍了gin通过go build -tags实现json包切换及库分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
gin的json库分析
在github.com/gin-gonic/gin/internal/json包下,存在两个文件
一个是json.go,一个是jsoniter.go
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.
// +build !jsoniter
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
// 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.
// +build jsoniter
package json
import "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包提供的Marshal、Unmarshal等方法,默认编译时,会采用官方的json库,当tags参数等于jsoniter时,则会采用jsoniter库
go build -tags=jsoniter .
go build - tags
通过在代码中增加注释//+build xxx时,编译时传递对应的tags值,就会编译不同的文件。
- 构建约束以一行+build开始的注释。在+build之后列出了一些条件,在这些条件成立时,该文件应包含在编译的包中;
- 约束可以出现在任何源文件中,不限于go文件;
- +build必须出现在package语句之前,+build注释之后应要有一个空行。
参考 https://www.jb51.net/jiaoben/297334xjf.htm
以上就是gin通过go build -tags实现json包切换及库分析的详细内容,更多关于gin切换json包的资料请关注脚本之家其它相关文章!
