Build a Binary
Environment Variables
You can access environment variables using the os
package.
package main
import (
"fmt"
"os"
"strings"
)
func main() {
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
fmt.Println()
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
fmt.Println(pair[0], pair[1])
}
}
Embed Directive
//go:embed
is a compiler directive that allows programs to include arbitrary files and folders in the binary at build time.
Place the //go:embed
directive just before a variable declaration, and assign the result of the embed package's FS function to that variable.
package main
import (
"embed"
"fmt"
)
//go:embed static/*.txt
var content embed.FS
func main() {
// Use the embedded files
data, err := content.ReadFile("static/example.txt")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println("Content:", string(data))
}
Command Line Arguments
os.Args
provides access to raw command-line arguments.
package main
import (
"fmt"
"os"
)
func main() {
// The first element of os.Args is the name of the program itself
fmt.Println("Program Name:", os.Args[0])
fmt.Println("Command Line Arguments:", os.Args[1:])
if len(os.Args) > 1 {
fmt.Println("First Argument:", os.Args[1])
}
fmt.Println("All Arguments:")
for i, arg := range os.Args {
fmt.Printf("%d: %s\n", i, arg)
}
}
Try to run this locally to see the arguments.
go run main.go arg1 arg2 arg3
Command Line Flags
You can use the flag
package to work with command line flags.
package main
import (
"flag"
"fmt"
)
func main() {
var name string
var age int
var married bool
// StringVar, IntVar, and BoolVar define flags and store values in the provided variables
flag.StringVar(&name, "name", "Lite Rank", "The name of the person")
flag.IntVar(&age, "age", 20, "The age of the person")
flag.BoolVar(&married, "married", false, "Is the person married")
// Parse the command line arguments
flag.Parse()
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Married:", married)
}
You can run the program and provide values for the flags like this:
go run main.go -name="Alice" -age=25 -married=true
Command Line Subcommands
You can use the flag
package along with other packages like os
and fmt
to create subcommands in your command-line application.
A common approach is to use the os.Args
slice to check the command-line arguments and determine which subcommand is being executed.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// Define flags for the main command
var verbose bool
flag.BoolVar(&verbose, "verbose", false, "Enable verbose mode")
// Parse the main command flags
flag.Parse()
// Check if there are any arguments (subcommands)
if len(os.Args) < 2 {
fmt.Println("Usage: main [options] <subcommand> [subcommand-options]")
os.Exit(1)
}
// Switch on the subcommand
switch os.Args[1] {
case "subcommand1":
// Handle subcommand1
fmt.Println("Executing subcommand1")
fmt.Println("Verbose mode:", verbose)
case "subcommand2":
// Handle subcommand2
fmt.Println("Executing subcommand2")
fmt.Println("Verbose mode:", verbose)
default:
fmt.Println("Unknown subcommand:", os.Args[1])
os.Exit(1)
}
}
You can run the program with subcommands and additional options like this:
go run main.go -verbose subcommand1
Go Build
The go build
command in Go is used to compile the Go source code files.
When you run go build
without any arguments, it compiles the Go program in the current directory and creates an executable file with the same name as the last element of the current directory's path.
Specify Ouput File
You can specify the name of the output file using the -o
flag:
go build -o output_binary_filename
Build for Different Platforms
You can use the GOOS and GOARCH environment variables to build for a different operating system or architecture:
GOOS=linux GOARCH=amd64 go build
Keep Going! Keep Learning!