Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > gin切换json包

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包提供的MarshalUnmarshal等方法,默认编译时,会采用官方的json库,当tags参数等于jsoniter时,则会采用jsoniter

go build -tags=jsoniter .

go build - tags

通过在代码中增加注释//+build xxx时,编译时传递对应的tags值,就会编译不同的文件。

 参考 https://www.jb51.net/jiaoben/297334xjf.htm 

以上就是gin通过go build -tags实现json包切换及库分析的详细内容,更多关于gin切换json包的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文