feat: add env file support and parameterize SQL queries
Add .env and .env.local loading with InitEnv() helper that reads environment variables from config files without overwriting existing values. Refactor SQL queries to use parameterized arguments instead of string formatting for LIMIT/OFFSET clauses, improving query security and preventing SQL injection vulnerabilities. Clean up unnecessary rows.Close() calls and simplify error handling in database query functions.
This commit is contained in:
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -23,6 +24,28 @@ func loadConfig() Config {
|
||||
}
|
||||
}
|
||||
|
||||
func loadEnvFile(envFile string) {
|
||||
if _, err := os.Stat(envFile); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(envFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, line := range splitLines(data) {
|
||||
parts := splitKV(line)
|
||||
if len(parts) == 2 {
|
||||
key := parts[0]
|
||||
value := unquote(parts[1])
|
||||
if os.Getenv(key) == "" {
|
||||
os.Setenv(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
@@ -39,3 +62,53 @@ func parseDuration(key string, defaultVal time.Duration) time.Duration {
|
||||
}
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
func splitLines(data []byte) []string {
|
||||
lines := make([]string, 0)
|
||||
var line string
|
||||
for _, b := range data {
|
||||
if b == '\n' {
|
||||
lines = append(lines, line)
|
||||
line = ""
|
||||
} else if b != '\r' {
|
||||
line += string(b)
|
||||
}
|
||||
}
|
||||
if line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func splitKV(line string) []string {
|
||||
for i, b := range line {
|
||||
if b == '=' {
|
||||
return []string{line[:i], line[i+1:]}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unquote(s string) string {
|
||||
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
if len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'' {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func InitEnv() {
|
||||
possibleFiles := []string{
|
||||
".env",
|
||||
".env.local",
|
||||
}
|
||||
for _, f := range possibleFiles {
|
||||
abs, err := filepath.Abs(f)
|
||||
if err == nil {
|
||||
loadEnvFile(abs)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user