In golang project, we may need to call os environment variable for security purposes in OSX or Linux.

Here will showing how to set global environment and get value in our golang project.

Setting global variable

In here, we setting global environment variable in .bash_profile

Open .bash_profile and setting variable

vim ~/.bash_profile

Setting your variable like bellow:

expore APP_KEYGEN = "your security keygen"
export APP_HOST = "host address"

After we setting our variable, we need to reload variable into the environment by source:

source ~/.bash_profile

Try to get global environment variable:

(Notify! You need to reopen your IDE or terminal if not get the environment)

echo $APP_HOST

Get environment in golang

In golang can use os package’s Getena get environment variable:


package main

import (

func main() {
        APP_KEYGEN := os.Getenv("APP_KEYGEN")
        APP_HOST := os.Getenv("APP_HOST")
        fmt.Println(APP_KEYGEN, APP_HOST)

Try to execute and print our env value:

go run main.go


If os.Getenv return empty(null), cannot get os.Getenv, you should reopen IDE, terminal, or reload source.