通過在代碼中使用+build tags值
互拾,編譯時(shí)傳遞相應(yīng)的tags值踱葛,可以實(shí)現(xiàn)自動(dòng)選擇編譯相應(yīng)的代碼捌锭。
1.執(zhí)行aa.go
aa/aa.go文件
// +build !2
package aa
var (
Name = "Jack"
)
aa/aa2.go文件
// +build 2
package aa
var (
Name = "Helen"
)
main.go文件
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gisxiaowei/gin-demo/aa"
)
func main() {
router := gin.Default()
router.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, aa.Name)
})
router.Run(":8080")
}
VSCode launch.json文件
{
// 使用 IntelliSense 了解相關(guān)屬性肯腕。
// 懸停以查看現(xiàn)有屬性的描述挨厚。
// 欲了解更多信息堡僻,請(qǐng)?jiān)L問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${fileDirname}",
"env": {},
"args": [],
"showLog": true
}
]
}
http://localhost:8080/hello執(zhí)行結(jié)果為Jack。
2.執(zhí)行aa2.go
通過增加"buildFlags": "-tags=2"幽崩,將參數(shù)傳遞給go編譯器
{
// 使用 IntelliSense 了解相關(guān)屬性苦始。
// 懸停以查看現(xiàn)有屬性的描述。
// 欲了解更多信息慌申,請(qǐng)?jiān)L問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${fileDirname}",
"env": {},
"args": [],
"showLog": true,
"buildFlags": "-tags=2"
}
]
}
http://localhost:8080/hello執(zhí)行結(jié)果為Helen陌选。
轉(zhuǎn)載請(qǐng)注明:作者gisxiaowei,首發(fā)簡(jiǎn)書 jianshu.com