Created
March 21, 2024 12:07
-
-
Save ae5259/f3cfc7365db535ea83dad932ac06c53e to your computer and use it in GitHub Desktop.
My own .env reader function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
) | |
func ReadENV(key string) (value string) { | |
var result string | |
path, err := os.Getwd() | |
if err != nil { | |
fmt.Println("Error occurred while getting path:", err.Error()) | |
} | |
_, ok := strings.CutSuffix(path, "/") | |
var filepath string | |
if ok { | |
filepath = path + ".env" | |
} else { | |
filepath = path + "/" + ".env" | |
} | |
content, err := os.ReadFile(filepath) | |
if err != nil { | |
fmt.Println("Error occurred while reading file ", filepath, " error: ", err.Error()) | |
} | |
lines := strings.Split(string(content[:]), "\n") | |
for _, line := range lines { | |
if strings.Contains(line, key) { | |
result = strings.Split(line, fmt.Sprintf("%s=", key))[1] | |
} | |
} | |
if strings.Contains(result, `"`) || strings.Contains(result, "'") { | |
result = strings.ReplaceAll(result, `"`, "") | |
result = strings.ReplaceAll(result, `'`, "") | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment