golang根据tags执行不同的代码

通过在代码中使用+build tags值,编译时传递相应的tags值,可以实现自动选择编译相应的代码。

1.执行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 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: 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执行结果为Jack。

2.执行aa2.go

通过增加"buildFlags": "-tags=2",将参数传递给go编译器

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: 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执行结果为Helen。

转载请注明:作者gisxiaowei,首发 jianshu.com

你可能感兴趣的:(golang根据tags执行不同的代码)