How to create a custom build tag in Go
Custom build tags in Go allow conditional compilation based on environment, architecture, or custom scenarios by using //go:build tags at the top of files, which are then enabled via go build -tags "tagname", supporting logical operators like &&, ||, and ! for complex conditions, and enabling clean separation of environment-specific code when consistently applied across files, as demonstrated with devmode and prod tags, where go build -tags "devmode,!prod" includes only files matching devmode and excluding prod, making it a powerful, straightforward mechanism for build-time code inclusion.
In Go, custom build tags (also known as build constraints) allow you to control which files should be included or excluded during the build process based on specific conditions. This is useful for writing code that should only compile in certain environments, architectures, operating systems, or custom-defined scenarios.
To create a custom build tag, follow these guidelines:
1. Place the build tag at the top of the Go file
A build tag must be placed near the top of a Go source file, before the package
declaration, with exactly one blank line separating it from the package
statement. It should be formatted as a comment.
//go:build customtag // build customtag package main
⚠️ Note: The second line (
build
) is legacy syntax but still supported. The//go:build
syntax is preferred since Go 1.17.
2. Use consistent tags across relevant files
Suppose you want to define a custom build tag called devmode
. You can tag specific files like this:
//go:build devmode // build devmode package main import "fmt" func init() { fmt.Println("Development mode enabled") }
Save this file as, for example, dev_only.go
.
Now, this file will only be included when you build with the devmode
tag:
go build -tags devmode
If you run go build
without -tags devmode
, this file will be ignored.
3. Combine custom tags with logical operators
You can use boolean logic with build tags:
//go:build linux && customtag
//go:build customtag || experimental
//go:build !prod
Example:
//go:build devmode && !prod package main
This file is included only if devmode
is set and prod
is not.
When building:
go build -tags "devmode,!prod"
4. Use tags to separate environment-specific code
A common use case is having different implementations for development, testing, or staging.
For example:
api_dev.go
→//go:build dev
api_prod.go
→//go:build prod
Then build accordingly:
go build -tags dev # or go build -tags prod
5. Multiple tags in one command
You can specify multiple tags when building:
go build -tags "devmode,featureauth,linux"
This enables all three tags. The file constraints will be evaluated accordingly.
6. Verify which files are included
To see which files are being compiled (helpful for debugging), use:
go list -f '{{.GoFiles}}' -tags devmode
This shows the list of Go files that would be included with the devmode
tag.
Summary
- Use
//go:build yourtag
at the top of the file. - Build with
go build -tags yourtag
. - Combine tags using
&&
,||
,!
. - Keep tag names consistent and meaningful (e.g.,
debug
,enterprise
,testdb
). - Avoid spaces in tag lists when passing via
-tags
; use commas instead.
Custom build tags are a clean way to manage conditional compilation without changing code or using external scripts. They’re widely used in large projects for platform-specific logic or feature flags.
Basically, just tag your files and control inclusion at build time. Not complex, but powerful when used right.
The above is the detailed content of How to create a custom build tag in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

FornewGo1.21 projects,useslogforofficialstructuredloggingsupport;2.Forhigh-performanceproductionservices,chooseZaporZerologduetotheirspeedandlowallocations;3.ForeaseofuseandrichintegrationslikeSlackorSentryhooks,Logrusisidealdespitelowerperformance;4

UseURLpathversioninglike/api/v1forclear,routable,anddeveloper-friendlyversioning.2.Applysemanticversioningwithmajorversions(v1,v2)only,avoidingmicro-versionslikev1.1topreventroutingcomplexity.3.OptionallysupportcontentnegotiationviaAcceptheadersifalr

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

In Go, creating and using custom error types can improve the expressiveness and debugability of error handling. The answer is to create a custom error by defining a structure that implements the Error() method. For example, ValidationError contains Field and Message fields and returns formatted error information. The error can then be returned in the function, detecting specific error types through type assertions or errors.As to execute different logic. You can also add behavioral methods such as IsCritical to custom errors, which are suitable for scenarios that require structured data, differentiated processing, library export or API integration. In simple cases, errors.New, and predefined errors such as ErrNotFound can be used for comparable

The correct way to process signals in Go applications is to use the os/signal package to monitor the signal and perform elegant shutdown. 1. Use signal.Notify to send SIGINT, SIGTERM and other signals to the channel; 2. Run the main service in goroutine and block the waiting signal; 3. After receiving the signal, perform elegant shutdown with timeout through context.WithTimeout; 4. Clean up resources such as closing database connections and stopping background goroutine; 5. Use signal.Reset to restore the default signal behavior when necessary to ensure that the program can be reliably terminated in Kubernetes and other environments.

Using structured logging, adding context, controlling log levels, avoiding logging sensitive data, using consistent field names, correctly logging errors, taking into account performance, centrally monitoring logs and unifying configurations are best practices in Go to achieve efficient logging. First, structured logs in JSON format (such as using uber-go/zap or rs/zerolog) facilitate machine parsing and integrating ELK, Datadog and other tools; second, log traceability is enhanced by requesting context information such as ID and user ID, and can be injected through context.Context or HTTP middleware; third, use Debug, Info, Warn, Error levels reasonably, and operate through environment variables.
