🥅 handled unhandled errors + moved default config from code to .env file

This commit is contained in:
Hacki 2023-10-05 23:18:02 +02:00 committed by Akinimaginable
parent 1f98250626
commit a644e95044
4 changed files with 44 additions and 22 deletions

7
.env
View file

@ -0,0 +1,7 @@
PLAKKEN_INTERFACE=0.0.0.0
PLAKKEN_PORT=3000
PLAKKEN_REDIS_ADDR=localhost:6379
PLAKKEN_REDIS_USER=
PLAKKEN_REDIS_PASSWORD=
PLAKKEN_REDIS_DB=0
PLAKKEN_REDIS_URL_LEN=5

View file

@ -1,6 +1,8 @@
package main
import (
"github.com/joho/godotenv"
"log"
"os"
"strconv"
)
@ -15,38 +17,40 @@ type config struct {
urlLength int
}
func setConfig() config {
host := os.Getenv("PLAKKEN_HOST")
func getConfig() config {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
port := os.Getenv("PLAKKEN_PORT")
if port == "" {
port = "3000"
}
redisAddr := os.Getenv("PLAKKEN_REDIS_ADDR")
if redisAddr == "" {
redisAddr = "localhost:6379"
db := os.Getenv("PLAKKEN_REDIS_DB")
uLen := os.Getenv("PLAKKEN_REDIS_URL_LEN")
if port == "" || redisAddr == "" {
log.Fatal("Missing or invalid PLAKKEN_PORT or PLAKKEN_REDIS_ADDR")
}
redisUser := os.Getenv("PLAKKEN_REDIS_USER")
redisPassword := os.Getenv("PLAKKEN_REDIS_PASSWORD")
redisDB, err := strconv.Atoi(os.Getenv("PLAKKEN_REDIS_DB"))
redisDB, err := strconv.Atoi(db)
if err != nil {
redisDB = 0
log.Fatal("Invalid PLAKKEN_REDIS_DB")
}
urlLength, err := strconv.Atoi("PLAKKEN_URL_LENGTH")
urlLen, err := strconv.Atoi(uLen)
if err != nil {
urlLength = 3
log.Fatal("Invalid PLAKKEN_REDIS_URL_LEN")
}
s := config{
host: host,
conf := config{
host: os.Getenv("PLAKKEN_INTERFACE"),
port: port,
redisAddr: redisAddr,
redisUser: redisUser,
redisPassword: redisPassword,
redisUser: os.Getenv("PLAKKEN_REDIS_USER"),
redisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
redisDB: redisDB,
urlLength: urlLength,
urlLength: urlLen,
}
return s
return conf
}

6
go.mod
View file

@ -2,8 +2,12 @@ module plakken
go 1.21
require (
github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.2.1
)
require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/redis/go-redis/v9 v9.2.1 // indirect
)

11
main.go
View file

@ -3,6 +3,7 @@ package main
import (
"fmt"
"io"
"log"
"net/http"
"strings"
)
@ -42,12 +43,18 @@ func handleRequest(w http.ResponseWriter, r *http.Request) {
}
func main() {
currentConfig = setConfig()
currentConfig = getConfig()
listen := currentConfig.host + ":" + currentConfig.port
http.HandleFunc("/", handleRequest)
if currentConfig.host == "" {
fmt.Println("Listening on port " + listen)
} else {
fmt.Println("Listening on " + listen)
}
err := http.ListenAndServe(listen, nil)
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
}