dongtanjian9310 2015-05-24 19:11
浏览 40
已采纳

我可以通过构建命令标志并读取内部代码吗?

I want in init function to execute one of those two lines

func init() {
    log.SetPrefix(">>>>>>>>>>>>>   ")


    log.SetOutput(ioutil.Discard)
}

How to achieve something similiar to C and macro definition in make file ? I build go program like go build my_project and I don't have any custom make file. Can I pass to build command flag and read inside code ?

  • 写回答

1条回答 默认 最新

  • duansha8764 2015-05-24 19:43
    关注

    Create a string variable that you can test. Then set that string variable using -X passed to the linker. For example:

    package main
    
    var MODE string
    
    func main() {
        if MODE == "PROD" {
            println("I'm in prod mode")
        } else {
            println("I'm NOT in prod mode")
        }
    
    }
    

    Now, if you build this with just go build, MODE will be "". But you can also build it this way:

    go build -ldflags "-X main.MODE PROD"
    

    And now MODE will be "PROD". You can use that to modify your logic based on build settings. I generally use this technique to set version numbers in the binary; but it can be used for all kinds of build-time configuration. Note that it can only set strings. So you couldn't make MODE a bool or integer.


    You can also achieve this with tags, which are slightly more complicated to set up, but much more powerful. Create three files:

    main.go

    package main
    
    func main() {
        doThing()
    }
    

    main_prod.go

    // +build prod
    
    package main
    
    func doThing() {
        println("I'm in prod mode")
    }
    

    main_devel.go

    // +build !prod
    
    package main
    
    func doThing() {
        println("I'm NOT in prod mode")
    }
    

    Now when you build with go build, you'll get your main_devel.go version (the filename doesn't matter; just the // +build !prod line at the top). But you can get a production build by building with go build -tags prod.

    See the section on Build Constraints in the build documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端