working on ron-example
This commit is contained in:
@@ -2,11 +2,52 @@ package config
|
||||
|
||||
import (
|
||||
"aidanwoods.dev/go-paseto"
|
||||
"bufio"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func New() *App {
|
||||
var err error
|
||||
|
||||
err = loadEnvFile()
|
||||
if err != nil {
|
||||
slog.Error("error loading env file", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var durationTime time.Duration
|
||||
var ak paseto.V4AsymmetricSecretKey
|
||||
|
||||
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("ASYMMETRICKEY"))
|
||||
if err != nil {
|
||||
ak = paseto.NewV4AsymmetricSecretKey()
|
||||
}
|
||||
pk := ak.Public()
|
||||
|
||||
duration := os.Getenv("DURATION")
|
||||
if duration != "" {
|
||||
durationTime, err = time.ParseDuration(duration)
|
||||
if err != nil {
|
||||
durationTime = time.Hour * 24 * 7
|
||||
}
|
||||
}
|
||||
|
||||
return &App{
|
||||
DataSource: os.Getenv("DATASOURCE"),
|
||||
Security: Security{
|
||||
AsymmetricKey: ak,
|
||||
PublicKey: pk,
|
||||
Duration: durationTime,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type App struct {
|
||||
Security Security
|
||||
DataSource string
|
||||
Security Security
|
||||
}
|
||||
|
||||
type Security struct {
|
||||
@@ -14,3 +55,27 @@ type Security struct {
|
||||
PublicKey paseto.V4AsymmetricPublicKey
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
func loadEnvFile() error {
|
||||
file, err := os.Open(".env")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if len(line) == 0 || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(line, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSpace(parts[0])
|
||||
value := strings.TrimSpace(parts[1])
|
||||
os.Setenv(key, value)
|
||||
}
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
func NewPostgresPool(dataSource string) *pgxpool.Pool {
|
||||
dbPool, err := pgxpool.New(context.Background(), dataSource)
|
||||
if err != nil {
|
||||
slog.Error("error connecting to database", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err := dbPool.Ping(context.Background()); err != nil {
|
||||
slog.Error("error pinging database, maybe incorrect datasource", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
slog.Info("connected to database")
|
||||
return dbPool
|
||||
}
|
||||
Reference in New Issue
Block a user