1. 条件编译
Go
GoBuild Constraints
build tag
2. 编译标签
编译标签是一种通过在源码文件顶部添加注释,来决定文件是否参与编译的约束方式。其格式如下:
// +build <tags>
// +build
// +build linux
// main package comment
package main
Go
tags
ORAND!NOT+build与
标签可以指定为以下内容:
GOOSlinuxdarwinwindowsGOARCHamd64x86i386gcgccgoCGOcgogoGo Version 1.1go1.1Go Version 1.12go1.12
go build -tags
使用示例:
(linux AND 386) OR (darwin AND (NOT cgo))
// +build linux,386 darwin,!cgo
(linux OR darwin) AND amd64
// +build linux darwin
// +build amd64
ignore
// +build ignore
linuxwindows amd64
// +build linux windows,amd64
package main
+build+build
Gininternal/jsonjsonjsonjsoniter
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 等函数都由 Gin 下的 json 包导出
Marshal = json.Marshal
Unmarshal = json.Unmarshal
MarshalIndent = json.MarshalIndent
NewDecoder = json.NewDecoder
NewEncoder = json.NewEncoder
)
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 等函数都由 Gin 下的 json 包导出
Marshal = json.Marshal
Unmarshal = json.Unmarshal
MarshalIndent = json.MarshalIndent
NewDecoder = json.NewDecoder
NewEncoder = json.NewEncoder
)
Ginencoding/jsonjson
$ go build -tags=jsoniter .
jsoniter.go
$ go build -tags=go_json .
Gin-tags=jsoniterjsoniter.gojsonjsoniterjsonjsonGinjson
3. 文件后缀
除了编译标签,第二种添加编译约束的方法是通过源码文件的文件名实现的,这种方案比构造标签方案更简单。编译器也会根据文件后缀来自动选择编译文件:
$filename_$GOOS.go
$filename_$GOARCH.go
$filename_$GOOS_$GOARCH.go
$filename$GOOS$GOARCH
$filename_$GOOS_$GOARCH.go
os
构建标签和文件名后缀在功能上是重叠的,根据需要选择合适的就行。