Saturday 9 October 2021

How To Get The List Of All Environment Variables Key Used In A Golang Module/Project.

In this Articles We are going to cover up a real problem. When ever we separate independent modules from a big project to small it becomes hard to measure every aspects of the code for example how many external files we're using for that module, which db connection we're using for the module and also the most important part how many Environment Variables or we can call env variables we're using for that module.

These are real world problems and doing these all things manually can be pain in ass, So for avoiding these kind of problems we're going to implement a program/Tool, Which is going to extract all the environment variables(env) key used in a golang module.

How We're going to achieve that, for that we needed a flow to understand.

In Golang we uses os.Getenv("key") to get the environment variable value so we've got the pattern to achieve that.

1. Pattern

we have to check each file inside a module/project for os.Getenv("key") if we found any pattern while checking the golang file we're going to extract that element from that file or from line with the help of regular expression.


2. Regular Expression(regexp)

we're about to use regular expression to check the pattern in each file's each line to get our results. The function from regexp package we're going to use to extract information is FindlString.


3. FindString function Defination

FindString returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use FindStringIndex or FindStringSubmatch if it is necessary to distinguish these cases.

So now we've know everything we needed to know before writing program let's start writing code


4. Directory Path Command


5. Walking On Directory/Module Recursivly to Get All Golang Files.

we're going to use walk function of filepath package to get all the files which have .go extension

Walk is less efficient than WalkDir, introduced in Go 1.16,
which avoids calling os.Lstat on every visited file or directory.

So wer're checking for each in this block to get the all .go extension files one by one.

6. Iterating Over All Files One By One

This portion of the code is the most important part and in this we're reading each file and after reading doing parsing see the code below.

Full Code

Labels: , ,

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home