ldflags
介绍 (Introduction)
When deploying applications into a production environment, building binaries with version information and other metadata will improve your monitoring, logging, and debugging processes by adding identifying information to help track your builds over time. This version information can often include highly dynamic data, such as build time, the machine or user building the binary, the Version Control System (VCS) commit ID it was built against, and more. Because these values are constantly changing, coding this data directly into the source code and modifying it before every new build is tedious and prone to error: Source files can move around and variables/constants may switch files throughout development, breaking the build process.
在将应用程序部署到生产环境中时,使用版本信息和其他元数据构建二进制文件会通过添加标识信息来帮助您跟踪构建情况,从而改善您的监视,日志记录和调试过程。 此版本信息通常可以包括高度动态的数据,例如构建时间,构建二进制文件的机器或用户,针对其构建的版本控制系统(VCS)提交ID等。 由于这些值一直在变化,因此在每个新版本繁琐且容易出错之前,将这些数据直接编码为源代码并进行修改:源文件会四处移动, 变量/常量可能会在整个开发过程中切换文件,从而破坏了构建过程。
One way to solve this in Go is to use -ldflags
with the go build
command to insert dynamic information into the binary at build time, without the need for source code modification. In this flag, ld
stands for linker, the program that links together the different pieces of the compiled source code into the final binary. ldflags
, then, stands for linker flags. It is called this because it passes a flag to the underlying Go toolchain linker, cmd/link
, that allows you to change the values of imported packages at build time from the command line.
在Go中解决此问题的一种方法是在构建时将-ldflags
与go build
命令一起使用,以将动态信息插入二进制文件中,而无需修改源代码。 在此标志中, ld
代表linker ,该程序将已编译的源代码的不同部分链接到最终的二进制文件中。 ldflags
代表链接器标志 。 之所以这样称呼,是因为它向基础Go工具链链接器cmd/link
传递了一个标志,该标志使您可以在构建时从命令行更改导入包的值。
In this tutorial, you will use -ldflags
to change the value of variables at build time and introduce your own dynamic information into a binary, using a sample application that prints version information to the screen.
在本教程中,您将使用-ldflags
在构建时更改变量的值,并使用将版本信息打印到屏幕的示例应用程序将自己的动态信息引入二进制文件。
先决条件 (Prerequisites)
To follow the example in this article, you will need:
要遵循本文中的示例,您将需要:
A Go workspace set up by following How To Install Go and Set Up a Local Programming Environment.
通过遵循如何安装Go和设置本地编程环境来设置 Go工作区。
构建示例应用程序 (Building Your Sample Application)
Before you can use ldflags
to introduce dynamic data, you first need an application to insert the information into. In this step, you will make this application, which will at this stage only print static versioning information. Let’s create that application now.
在使用ldflags
引入动态数据之前,首先需要一个应用程序来将信息插入其中。 在此步骤中,您将创建此应用程序,该应用程序在此阶段将仅打印静态版本控制信息。 现在创建该应用程序。
In your src
directory, make a directory named after your application. This tutorial will use the application name app
:
在src
目录中,建立一个以应用程序命名的目录。 本教程将使用应用程序名称app
:
mkdir app
mkdir 应用
Change your working directory to this folder:
将工作目录更改为此文件夹:
cd app
光盘应用
Next, usi