0

I have two packages in Go, and I'm encountering an issue when printing the value of a secret variable. When I try to print it using fmt.Println(secret), it displays an empty byte slice like []. Is this behavior normal?

Here's an example of the code in both packages:

package test

import (
    "fmt"
    "os"
)
var secret = []byte(os.Getenv("SECRET"))

func Init() {
  fmt.Println(secret)
}
package main

import (
    "example/test"
    "github.com/joho/godotenv"
    "log"
)

func main() {
  if err := godotenv.Load(); err != nil {
    log.Fatal(err)
   }   
  test.Init()
}
AliZad64
  • 9
  • 2
  • Check the env variable `SECRET` configured properly. Looks like `SECRET` is not set or its value is empty, – PRATHEESH PC Jul 02 '23 at 09:14
  • It is, I have noticed if I call any `env` variable inside functions they return value but outside function they always return empty value – AliZad64 Jul 02 '23 at 09:17
  • I cannot reproduce that behavior. It works both for local and global variables. – isaactfa Jul 02 '23 at 09:25
  • im really sorry @isaactfa and @pratheesh-pc i forgot to add `godotenv` library because i use it to load `env` variables and then call them normally – AliZad64 Jul 02 '23 at 09:38
  • 3
    The call to `godotenv.Load` cannot affect the value of `secret` because `secret` is initialized at program startup. – Paul Hankin Jul 02 '23 at 09:45

1 Answers1

0

Change your test package function from :

var secret = []byte(os.Getenv("SECRET"))

func Init() {
    fmt.Println(secret)
}

to

func Init() {

    var secret = []byte(os.Getenv("SECRET"))
    fmt.Println(secret)
}

In the first code snippet, the variable secret is declared outside the Init function, which means it is a package-level variable and can be accessed by any function in the same package. When Init is called, it simply prints the value of secret that was previously assigned outside the function.

In the second code snippet, the variable secret is declared inside the Init function, which means it is a local variable and can only be accessed within the Init function itself. When Init is called, it assigns the value of os.Getenv("SECRET") to the secret variable and then prints it.

So, the main difference between these two code snippets is the scope of the secret variable. If you only need to use secret within the Init function, it's better to declare it inside the function to avoid cluttering the package-level scope with unnecessary variables. On the other hand, if you need to use secret in multiple functions within the same package, it may make sense to declare it as a package-level variable.

Output: [83 84 65 67 75 79 86 69 82 70 76 79 87]

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55