• 展开微博窗口
  • QQ:52619941
  • 微信:cnmemory
  • 展开分类目录
  • 还没有账号?

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值,就会编译不同的文件。

  1. 构建约束以一行+build开始的注释。在+build之后列出了一些条件,在这些条件成立时,该文件应包含在编译的包中;
  2. 约束可以出现在任何源文件中,不限于go文件;
  3. +build必须出现在package语句之前,+build注释之后应要有一个空行。

参考 https://www.jianshu.com/p/858a0791f618

码字很辛苦,转载请注明来自雨林寒舍《gin通过go build -tags实现json包的切换》

评论