feat: Remove godotenv. Replace it with our own function that reads .env on start

This commit is contained in:
Leo 2026-08-18 00:23:45 +03:00
parent 8440039362
commit 8d6889ce08
3 changed files with 31 additions and 6 deletions

View file

@ -1,20 +1,48 @@
package main
import (
"bufio"
"log"
"net/http"
"os"
"strings"
"go-backend/internal/database"
"go-backend/internal/database/sqlc"
"go-backend/internal/handlers"
"go-backend/internal/services"
"github.com/joho/godotenv"
)
// loadEnvFile sets environment variables from a KEY=VALUE .env file,
// without overriding vars already set in the environment.
func loadEnvFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
if _, exists := os.LookupEnv(key); exists {
continue
}
os.Setenv(key, strings.TrimSpace(value))
}
return scanner.Err()
}
func main() {
if err := godotenv.Load(); err != nil {
if err := loadEnvFile(".env"); err != nil {
log.Println("No .env file found")
}

1
go.mod
View file

@ -3,7 +3,6 @@ module go-backend
go 1.24.1
require (
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
golang.org/x/crypto v0.40.0
)

2
go.sum
View file

@ -1,5 +1,3 @@
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=