Golang переменные окружения windows

The GOPATH environment variable specifies the location of your workspace. If no GOPATH is set, it is assumed to be $HOME/go on Unix systems and %USERPROFILE%\go on Windows. If you want to use a custom location as your workspace, you can set the GOPATH environment variable. This page explains how to set this variable on various platforms.

  • Unix systems
    • Go 1.13
    • Bash
    • Zsh
    • fish
  • Windows
    • Go 1.13
    • Windows 10 (GUI)
    • Windows 10 (command line)

Unix systems

GOPATH can be any directory on your system. In Unix examples, we will set it to $HOME/go (the default since Go 1.8). Note that GOPATH must not be the same path as your Go installation. Another common setup is to set GOPATH=$HOME.

Go 1.13+

go env -w GOPATH=$HOME/go

Bash

Edit your ~/.bash_profile to add the following line:

export GOPATH=$HOME/go

Save and exit your editor. Then, source your ~/.bash_profile.

source ~/.bash_profile

Zsh

Edit your ~/.zshrc file to add the following line:

export GOPATH=$HOME/go

Save and exit your editor. Then, source your ~/.zshrc.

source ~/.zshrc

fish

set -x -U GOPATH $HOME/go

The -x is used to specify that this variable should be exported
and the -U makes this a universal variable, available to all sessions and
persistent.

Windows

Your workspace can be located wherever you like,
but we’ll use C:\go-work in this example.

NOTE: GOPATH must not be the same path as your Go installation.

  • Create a folder at C:\go-work.
  • Right-click on “Start” and click on “Control Panel”. Select “System and Security”, then click on “System”.
  • From the menu on the left, select the “Advanced system settings”.
  • Click the “Environment Variables” button at the bottom.
  • Click “New” from the “User variables” section.
  • Type GOPATH into the “Variable name” field.
  • Type C:\go-work into the “Variable value” field.
  • Click OK.

Go 1.13+ (command line)

  • Open a command prompt (Win + r then type cmd) or a powershell window (Win + i).
  • Type go env -w GOPATH=c:\go-work.

Windows 10 (GUI)

There is a faster way to edit Environment Variables via search:

  • Left click on “Search” and type env or environment.
  • Select “Edit environment variables for your account”.
  • … and follow steps above.

Windows 10 (command line)

  • Open a command prompt (Win + r then type cmd) or a powershell window (Win + i).
  • Type setx GOPATH %USERPROFILE%\go. (This will set the GOPATH to your [home folder]\go, such as C:\Users\yourusername\go.)
  • Close the command or PowerShell window. (The environment variable is only available for new command or PowerShell windows, not for the current window.)

This content is part of the Go Wiki.

GO или Golang – это высокопроизводительный и многопоточный язык программирования, разработанный компанией Google в 2007 году и выпущенный в 2009. По сей день, Golang продолжает набирать популярность. Согласно исследованию учебного центра IBS, в России этот язык входит в топ-5 по популярности и занимает 4 место на 2023 год. 

Image2

Изображение: selecty.ru

Язык программирования Go поддерживает множество операционных систем, что делает его универсальным выбором для разработки на различных платформах. В этом руководстве мы разберем шаг за шагом процесс установки Golang на Windows.

cloud

Go поддерживает Windows 7 и более новые версии. Убедитесь, что у вас установлена поддерживаемая версия ОС. 

В настоящем руководстве мы будем использовать Windows 11. Также нам понадобится пользователь с правами администратора для настройки переменных среды.

  1.  Чтобы установить Golang на Windows, пользователю необходимо скачать установочный файл последней версии для Microsoft Windows с официального сайта Go. При необходимости, вы можете выбрать вместо последней любую другую доступную версию языка.

Image6

  1. После окончания загрузки файла запускаем его и следуем рекомендациям мастера установки. При необходимости, вы можете изменить путь к расположению файлов. Он пригодится при настройке переменных среды.
  2. По завершению установки, проверим, что Golang успешно встал в систему. Для этого откроем терминал (Win + R → cmd) и выполним следующую команду:
go version

Если результат выполнения совпадает с тем, что на картинке ниже, значит Golang установлен успешно. Единственным отличием может быть версия языка, которую вы выбрали для установки на первом шаге инструкции.

Image3

Чтобы обновить Golang в Windows на более новую версию, необходимо удалить его старую версию и выполнить установку новой, согласно нашей инструкции.

Теперь перейдем к настройке переменных среды для корректной работы Go.

Настройка переменных среды

Настройка переменных среды — важный этап установки Go на Windows, который позволяет операционной системе определить, где находятся необходимые для работы Go файлы и каталоги.

Для корректной работы Golang потребуется две переменные среды:

  • GOPATH – это переменная среды, указывающая на место, где Go хранит загруженные и скомпилированные пакеты;
  • PATH – это переменная среды, позволяющая системе находить исполняемые файлы Go без указания полного пути к ним.

GOPATH

  1. В первую очередь настроим переменную среды GOPATH. Для этого пользователю необходимо организовать рабочее пространство, в котором будут храниться файлы и проекты на Go. 

В рамках инструкции мы создадим рабочее пространство по адресу C:\GoProject. Также добавим в данный каталог 2 папки:

  • bin – для хранения исполняемых файлов (бинарных файлов). Когда вы компилируете свой проект, Go создает исполняемый файл и размещает его в этом каталоге.;
  • src – для хранения исходных файлов Go. Все файлы .go размещаются именно здесь.

Image1

  1. После создания рабочего пространства настроим переменную GOPATH. Для этого перейдем в панель управления, затем на вкладку «Система и безопасность», далее «Система» и наконец кликаем на «Дополнительные параметры системы». 

Есть также более простой способ доступа к свойствам системы: открыть окно «Выполнить» (Win + R) и ввести:

sysdm.cpl

Image4

  1. В открывшемся окне кликаем на «Переменные среды», после чего нажимаем на кнопку «Создать» под переменными среды пользователя. Здесь необходимо заполнить два поля: имя переменной и ее значение.

В поле «Имя переменной» указываем GOPATH, а в поле «Значение переменной» – путь к созданному ранее рабочему пространству (в нашем случае C:\GoProject), как показано на рисунке ниже.

Image7

Нажимаем два раза кнопку «OK», чтобы сохранить внесенные изменения.

  1. Чтобы проверить создание системной переменной, откроем окно «Выполнить» (Win + R) и введем строку %GOPATH%. Если все было сделано правильно, перед вами откроет ваше рабочее пространство.

PATH

  1. Значение переменной PATH должно было добавиться автоматически после установки Go в систему. Чтобы это проверить, зайдем в переменные среды, повторив действия из второго шага прошлого подраздела.
  2. В открывшемся окне необходимо найти PATH среди системных переменных. Чтобы посмотреть ее значения, кликаем по ней два раза. 

В открывшемся окне должна быть запись, которая хранит путь до папки bin языка Go.

Image8

В нашем случае это C:\Program Files\Go\bin. Если ваше значение не соответствует тому, что было указано при установке Go, поменяйте его на корректное с помощью кнопки «Изменить».

На этом установка Golang в Windows и настройка переменных среды окончена. Теперь мы можем проверить его работу, написав и запустив свою первую программу.

Проверка установки

  1. Чтобы проверить работу только что установленного Golang в Windows, создадим тестовый файл с расширением .go в рабочем пространстве (C:\GoProject\src). Например, ExampleProgram.go.
  2. После создания файла добавим в него простой код:
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go has been successfully installed into your system!")
}

Продемонстрированная программа должна выводить сообщение об успешной установке Go в систему.

  1. Чтобы скомпилировать и запустить программу, вводим в терминал:
go run %GOPATH%/src/ExampleProgram.go

Как видно по картинке ниже, программа компилируется и выполняется, выводя на экран заданный текст.

Image5

Привет, Хабр! Представляю вашему вниманию перевод статьи A no-nonsense guide to environment variables in Go автора Enda Phelan.

Переменные окружения — лучший способ хранения конфигурации приложения, поскольку они могут быть заданы на системном уровне. Это один из принципов методологии Twelve-Factor App, он позволяет отделять приложения от системы, в которой они запущены (конфигурация может существенно различаться между деплоями, код не должен различаться).

Использование переменных окружения

Всё, что необходимо для взаимодействия с переменными окружения есть в стандартной библиотеке os. Вот так можно получить значение переменной окружения PATH:

package main

import (
    "fmt"
    "os"
)

func main() {
    // Store the PATH environment variable in a variable
    path, exists := os.LookupEnv("PATH")

    if exists {
        // Print the value of the environment variable
    	fmt.Print(path)
   }
}

А так — установить значение переменной:

package main

import (
    "fmt"
    "os"
)

func main() {
    // Set the USERNAME environment variable to "MattDaemon"
    os.Setenv("USERNAME", "MattDaemon")

    // Get the USERNAME environment variable
    username := os.Getenv("USERNAME")

    // Prints out username environment variable
    fmt.Print(username)
}

Загрузка переменных окружения из файла .env

На девелоперской машине, где сразу запущено много проектов, хранить параметры в переменных окружениях не всегда удобно; логичнее будет разделить их между проектами с помощью env-файлов. Сделать это можно, например, с помощью godotenv — это портированная на Go Ruby-библиотека dotenv. Она позволяет устанавливать необходимые для приложения переменные окружения из файла .env.

Чтобы установить пакет запустим:

go get github.com/joho/godotenv

Добавим настройки в файл .env в корне проекта:


GITHUB_USERNAME=craicoverflow
GITHUB_API_KEY=TCtQrZizM1xeo1v92lsVfLOHDsF7TfT5lMvwSno

Теперь можно использовать эти значения в приложении:

package main

import (
    "log"
    "github.com/joho/godotenv"
    "fmt"
    "os"
)

// init is invoked before main()
func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
        log.Print("No .env file found")
    }
}

func main() {
    // Get the GITHUB_USERNAME environment variable
    githubUsername, exists := os.LookupEnv("GITHUB_USERNAME")

    if exists {
	fmt.Println(githubUsername)
    }

    // Get the GITHUB_API_KEY environment variable
    githubAPIKey, exists := os.LookupEnv("GITHUB_API_KEY")
	
    if exists {
	 fmt.Println(githubAPIKey)
    }
}

Важно помнить, что если значение переменной окружения установлено на системном уровне, Go будет использовать именно это значение вместо указанного в env-файле.

Оборачиваем переменные окружения в конфигурационный модуль

Неплохо, конечно, иметь доступ к переменным окружения напрямую, как было показано выше, но вот поддерживать такое решение представляется довольно проблематичным. Имя переменной — это строка и, если оно изменится, то представьте себе головную боль, в которую выльется процесс обновления ссылок на переменную по всему приложению.

Чтобы решить эту проблему создадим конфигурационный модуль для работы с переменными окружения более централизованным и поддерживаемым способом.

Вот простой модуль config, который возвращает параметры конфигурации в структуре Config (также установим дефолтные значения параметров на случай, если переменной окружения в системе не окажется):

package config

import (
    "os"
)

type GitHubConfig struct {
    Username string
    APIKey   string
}

type Config struct {
    GitHub GitHubConfig
}

// New returns a new Config struct
func New() *Config {
    return &Config{
        GitHub: GitHubConfig{
	    Username: getEnv("GITHUB_USERNAME", ""),
	    APIKey: getEnv("GITHUB_API_KEY", ""),
	},
    }
}

// Simple helper function to read an environment or return a default value
func getEnv(key string, defaultVal string) string {
    if value, exists := os.LookupEnv(key); exists {
	return value
    }

    return defaultVal
}

Далее добавим типы в структуру Config, поскольку имеющееся решение поддерживает только строковые типы, а это не очень-то разумно для больших приложений.

Создадим хэндлеры для типов bool, slice и integer:

package config

import (
    "os"
    "strconv"
    "strings"
)

type GitHubConfig struct {
    Username string
    APIKey   string
}

type Config struct {
    GitHub    GitHubConfig
    DebugMode bool
    UserRoles []string
    MaxUsers  int
}

// New returns a new Config struct
func New() *Config {
    return &Config{
	GitHub: GitHubConfig{
	    Username: getEnv("GITHUB_USERNAME", ""),
	    APIKey:   getEnv("GITHUB_API_KEY", ""),
	},
	DebugMode: getEnvAsBool("DEBUG_MODE", true),
	UserRoles: getEnvAsSlice("USER_ROLES", []string{"admin"}, ","),
	MaxUsers:  getEnvAsInt("MAX_USERS", 1),
    }
}

// Simple helper function to read an environment or return a default value
func getEnv(key string, defaultVal string) string {
    if value, exists := os.LookupEnv(key); exists {
	return value
    }

    return defaultVal
}

// Simple helper function to read an environment variable into integer or return a default value
func getEnvAsInt(name string, defaultVal int) int {
    valueStr := getEnv(name, "")
    if value, err := strconv.Atoi(valueStr); err == nil {
	return value
    }

    return defaultVal
}

// Helper to read an environment variable into a bool or return default value
func getEnvAsBool(name string, defaultVal bool) bool {
    valStr := getEnv(name, "")
    if val, err := strconv.ParseBool(valStr); err == nil {
	return val
    }

    return defaultVal
}

// Helper to read an environment variable into a string slice or return default value
func getEnvAsSlice(name string, defaultVal []string, sep string) []string {
    valStr := getEnv(name, "")

    if valStr == "" {
	return defaultVal
    }

    val := strings.Split(valStr, sep)

    return val
}

Добавим в наш env-файл новые переменные окружения:


GITHUB_USERNAME=craicoverflow
GITHUB_API_KEY=TCtQrZizM1xeo1v92lsVfLOHDsF7TfT5lMvwSno
MAX_USERS=10
USER_ROLES=admin,super_admin,guest
DEBUG_MODE=false

Теперь можно использовать их в любом месте приложения:

package main

import (
    "fmt"
    "log"

    "github.com/craicoverflow/go-environment-variables-example/config"
    "github.com/joho/godotenv"
)

// init is invoked before main()
func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
	log.Print("No .env file found")
    }
}

func main() {
    conf := config.New()

    // Print out environment variables
    fmt.Println(conf.GitHub.Username)
    fmt.Println(conf.GitHub.APIKey)
    fmt.Println(conf.DebugMode)
    fmt.Println(conf.MaxUsers)

    // Print out each role
    for _, role := range conf.UserRoles {
	fmt.Println(role)
    }
}

Готово!

Да, существуют пакеты, предлагающие готовое решение для конфигурации вашего приложения, но насколько они необходимы, если это так легко сделать самостоятельно?

А как вы управляете конфигурацией в вашем приложении?

In this tutorial, I will be covering the basics around environment variables and some of the default and most used Golang environment variables. We will also learn how to set environment config from our golang programs.

Let’s begin!

What are the environment variables?

An environment variable is a name/value pair that is present outside of the program but can be referenced at a given time. There are a lot of environment variables which are already predefined in your system. Eg. $HOME

Trying running echo $HOME this will display your current user home directory. For me it’s like — /home/mohit . The result may vary based on your OS. Since I am using Ubuntu, the results might be different on your machine. But, concepts remains the same 😎

These environment variables can be set/unset or used anytime similar to how variables work in our programs.

You can see all the environment variables in your system with env command.


There are many variables that come with Golang when you install it and can be configured as per use. Some of the most used ones are —

GOROOT

This is the path where the Go standard library is located on your local filesystem. You generally won’t need to modify this unless you want to use some other versions of Go as well. It is set to /usr/local/<go-version> by default

GOPATH

This variable defines the root of your workspace. It tells Go where to look for your code. It stores all the files necessary for the development of the programs. It consists of three directories —

  • /bin — where go places binaries that go install compile
  • /pkg — location of compiled package code
  • /src — where your go code resides

By default, it is unset and points to a subdirectory named go in the user’s home directory. ($HOME/go on Unix, %USERPROFILE%\go on Windows)

Note from official Go docs. In module-aware mode —

  • Module cache is stored in the pkg/mod subdirectory of the first GOPATH directory.
  • Module source code outside the cache may be stored in any directory.
  • If GOPATH is not set, it defaults to the go subdirectory of the user’s home directory.

GOPROXY

A Go module proxy is any web server that can respond to GET requests
for URLs of a specified form.

GO proxy allows control over the download source and provides caching as well. This serves the zip archive of source code over HTTP making it faster.

You can use the proxy server by setting —

export GOPROXY=https://proxy.golang.org/

The above proxy is run by the Go team. To make changes permanent , add it to ~/.bashrc.

GOOS

GOOS defines the operating system for which to compile code. Examples are linux, darwin, windows, etc. This is an optional environment variable by default is set to empty.


Setting custom Env. variables/Configs in Go

Now that you have learned the basics of environment variables and some default ones provided by Go, you might be wondering to use it in your own projects. Configs should be used to store all kind of important information which can be easy to change. This also provides additional security to your passwords, secret keys to be directly available in your source code and are visible to anyone who has access to code.

Also, various environments require different configs. Like you would want to give different config in your test/development servers to those of production servers.

That’s a lot of explanation but it was required so that you don’t push secrets and use configs. There are a lot of ways to manage configs in go projects via .env,.json,.yaml, .toml and other formats. For simplicity, for now we will set the environment variables via code —

package main

import (
    "fmt"
    "os"
)

func main() {
    // Set an environment variable
    os.Setenv("SOME_VARIABLE", "SOME_VALUE")

    // Get the environment variable we set in previous step
    value := os.Getenv("SOME_VARIABLE")
    fmt.Println(value)

    // Unset an Environment Variable
    os.Unsetenv("SOME_VARIABLE")
    fmt.Println("After unset -> ", os.Getenv("SOME_VARIABLE"))
}
# Output
SOME_VALUE
After unset ->

Here, the program is pretty straightforward where we first set the variable and then fetch it with os.Getenv(), then we unset it using os.Unsetenv()

There are a couple of other useful methods —

  • os.Environ() — This returns all the environment variable which are set in key=value format.
  • os.LookupEnv() — This function combines the functionality of checking whether such variable exists, if yes then it returns the value.
  • os.Clearenv()— This method deletes all the environment variables and is useful when we are writing tests.

Well, it is not a good practice to use these secrets in your code directly. To solve this there are a number of libraries like godotenv, etc.

Here, the code below uses godotenv
You can get it using go get github.com/joho/godotenv

package main

import (
    "log"
    "github.com/joho/godotenv"
    "fmt"
    "os"
)

// init() is invoked before main()
// Loading variables before main() runs
func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
        log.Print(".env file not found")
    }
}

func main() {
    // Get the REDIS_PORT environment variable
    redisPort, found := os.LookupEnv("REDIS_PORT")
    if found {
        fmt.Println(redisPort)
    }
}

// Output based on .env below
6379

In this code, we first load the environment variables from a .env file in this project directory. Then, we fetch the REDIS_PORT key. The .env file looks like —

REDIS_PORT=6379

In case you are looking for pre-shipped packages, There are many useful open-source packages which help in managing environment configs —

  • Viper
  • Envconfig
  • Dotenv

Resources

  • Nice piece on environment variables
  • Go command line — learn about default env
  • Covers good ways to add configs

Awesome! You just learned how to manage configs in Golang. There are couple of other ways to manage configs in a better way, will cover them in some other article. I hope now you can easily add configs in your projects.

Liked the article? Consider supporting me ☕️


I hope you learned something new. Feel free to suggest improvements ✔️

I share regular updates and resources on Twitter. Let’s connect!

Keep exploring 🔎 Keep learning 🚀

Last Updated :
04 Feb, 2021

An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.

In Golang, we can use the os package to read and write environment variables.

1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.

os.Setenv(key,value)  

2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.

os.Getenv(key)

3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.

os.Unsetenv(key)

4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.

os.LookupEnv(key)

5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format.

os.Environ()

6. Delete all environment variables with os.Clearenv().

os.Clearenv()

Example 1:

Go

package main

import (

    "fmt"

    "os"

)

func main() {

    os.Setenv("GEEKS", "geeks")

    fmt.Println("GEEKS:", os.Getenv("GEEKS"))

    os.Unsetenv("GEEKS")

    value, ok := os.LookupEnv("GEEKS")

    fmt.Println("GEEKS:", value, " Is present:", ok)

}

Output:

Example 2:

Go

package main

import (

    "fmt"

    "os"

)

func main() {

    for _, env := range os.Environ() {

        fmt.Println(env)

    }

}

Output:

Example 3:
 

Go

package main

import (

    "fmt"

    "os"

)

func main() {

    os.Clearenv()

    fmt.Println("All environment variables cleared")

}

Output:

All environment variables cleared

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Установка diagbox на windows 7 64 bit
  • Synology hyper backup explorer windows
  • Прайс лист на установку windows
  • Минимальные требования для windows 10 home
  • Как получить доступ к системным папкам в windows 11