How to Set Environment Variables Programmatically in Go

Set environment variables in Go using os.Setenv or os.Unsetenv to modify runtime configuration.

Use os.Setenv to set an environment variable or os.Unsetenv to remove it within your Go program.

package main

import (
	"fmt"
	"os"
)

func main() {
	os.Setenv("MY_VAR", "my_value")
	os.Unsetenv("MY_VAR")
	fmt.Println("Done")
}

For runtime-only debugging settings like GODEBUG, set the GODEBUG environment variable before running the binary using os.Setenv or via the shell.