How to Get list of All Environment Variables' key Used in a Golang Module or Project
Kuldeep Singh
Posted on October 9, 2021
In this article we're about to write a program which helps us to get the all environment variables which is used in your project.
Why I created this program?
So recently in my current company we've decided to separate the modules which is not dependent on anycode, because the project structure was become larger that's why we decided to separate modules.
We moved code successfully but now comes problem how will you gonna get how many environment variables that separated module needed to run without causing any runtime issue.
So we decided to write a script to get the list of used environment variables used in that module.
How we are going to achieve this let's see the steps we needed to get the list of environment variables from module
- We're about to use command line argument which is going to be path of the module or project
- Reading module repository recursively using the filepath.Walk() function and only extracting the golang files full path.
- Here comes the main part, we're going to use regular expression for that because we know pattern of accessing environment variables in golang which is os.Getenv() function.
So let's start Writing Code Now:
Step 1.
dirPath := os.Args[1]
if &dirPath == nil {
fmt.Println("Argument can't be nil..")
os.Exit(2)
}
Step 2.
err := filepath.Walk(dirPath,
func(path string, d os.FileInfo, err error) error {
if err != nil {
return err
}
f := strings.Split(d.Name(), ".")
if f[len(f)-1] == "go" {
dir = append(dir, path)
}
return nil
})
if err != nil {
fmt.Println("Error to open directries..")
return
}
Step 3.
for _, f := range dir {
file, err := os.Open(f)
if err != nil {
e := ErrorArray{
Err: err,
File: f,
}
ErrArr = append(ErrArr, e)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
re := regexp.MustCompile(`os.Getenv(.*)`)
en := re.FindString(scanner.Text())
if len(en) == 0 {
continue
}
if strings.Contains(en, "+") {
n := strings.Split(en, "+")
for _, v := range n {
if strings.Contains(v, "os.Getenv") {
str := Replaced(v)
_, exists := MapArr[str]
if exists {
MapArr[str]++
continue
}
MapArr[str] = 1
}
}
continue
} else if strings.Contains(en, ",") {
n := strings.Split(en, ",")
for _, v := range n {
if strings.Contains(v, "os.Getenv") {
str := Replaced(v)
_, exists := MapArr[str]
if exists {
MapArr[str]++
continue
}
MapArr[str] = 1
}
}
continue
}
str := Replaced(en)
_, exists := MapArr[str]
if exists {
MapArr[str]++
continue
}
MapArr[str] = 1
}
file.Close()
}
If Have Any Queries Then Lemme Know
Read More : https://kdsingh4.blogspot.com/2021/10/how-to-get-list-of-all-environment.html
Also Subscribe My Channel To Support Me : https://www.youtube.com/channel/UCXhmNqWQ50zitqIdTgS7s8Q
Posted on October 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.