Added configuration from environment variables

This commit is contained in:
2025-02-08 16:27:33 +11:00
parent 1004dc9563
commit a842d09f96
7 changed files with 48 additions and 19 deletions

View File

@@ -1,19 +1,50 @@
package server
import (
"errors"
"fmt"
"net/http"
"os"
"projectreshoot/middleware"
"github.com/joho/godotenv"
)
type Config struct {
Host string
Port string
TrustedHost string
Host string
Port string
}
func NewServer() http.Handler {
func GetConfig() (*Config, error) {
err := godotenv.Load(".env")
if err != nil {
fmt.Println(".env file not found.")
}
config := &Config{
Host: os.Getenv("HOST"),
Port: os.Getenv("PORT"),
TrustedHost: os.Getenv("TRUSTED_HOST"),
}
if config.Host == "" {
return nil, errors.New("Envar not set: HOST")
}
if config.Port == "" {
return nil, errors.New("Envar not set: PORT")
}
if config.TrustedHost == "" {
return nil, errors.New("Envar not set: TRUSTED_HOST")
}
return config, nil
}
func NewServer(config *Config) http.Handler {
mux := http.NewServeMux()
addRoutes(
mux,
config,
)
var handler http.Handler = mux
handler = middleware.Logging(handler)