Load .env variables

Hello im trying to load .env variables with

dbConn := os.Getenv("DB")
fmt.Println("DB": , dbConn)

But dosn’t work, how do i load variables?

Works for me, (note I fixed the error where : is outside the quotes):

C:\path>type printenvvar.go
package main

import (

func main() {
        dbConn := os.Getenv("DB")
        fmt.Println("DB:", dbConn)

C:\path>set DB=db from env

C:\path>go run printenvvar.go
DB: db from env
1 Like

Hello, can i just read them from the .env file?
why i have to set them?

You can read whatever file you like, but that’s not the point of environment variables. Environment variable - Wikipedia


.env (“dotenv”) files seem to be a relatively recent thing and support is not built into Go. You have to find a 3rd party library to read your dotenv file and load its data into the process’s environment variables, such as joho/godotenv: A Go port of Ruby’s dotenv library (Loads environment variables from .env.) (github.com).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.