projects

holonet

A multiplayer video game backend in Go

feat: add env parsing and validation

daniel daum committed parent e3cb15b commit 0ec0e71Signed, not verified

SignedGitea couldn't verify the signature.

Showing 11 changed files with 262 additions and 5 deletions.

.gitignore +3 −0
@@ -30,3 +30,6 @@ go.work.sum3030# Editor/IDE3131# .idea/3232# .vscode/3334# temp35tmp
AGENTS.mdadded +50 −0
@@ -0,0 +1,50 @@1# Holonet23Tick-based MMO game server written in Go. A Godot client communicates with this4server over WebSockets. The server is authoritative: game state advances in a5fixed tick loop (goroutine). Design is early and evolving — currently a single6`main` package.78## Stack910- **Server:** Go, WebSocket API for the Godot client, tick-based game loop11- **Persistence:** Postgres (planned); Redis for caching (planned)12- **Blobs:** Cloudflare R2 if needed13- **Packaging/deploy:** Docker; local dev → self-hosted Dokploy PaaS (test) → production14- **Secrets:** self-hosted Infisical in dev; `.env` is local-only and gitignored1516## Commands1718- `just check` — format, lint (golangci-lint), and test. Run before finishing any task.19- `just run` / `just test` — dev server / tests only.20- Global tools come from mise (`mise.toml`); project dependencies via `go get` (`go.mod`).2122## Conventions2324- **Config:** env vars parsed once at startup in `env.go` (`parseEnv`). Defaults:25  `ENVIRONMENT=dev`, `PORT=8080`. Valid environments: `dev`, `test`, `prod`.26- **Errors:** return wrapped errors (`fmt.Errorf` with `%w`). Log-and-exit only in27  `main`; inner functions never call `os.Exit` or log errors they also return.28- **Logging:** `slog` with key-value attributes (`slog.Info("msg", "key", val)`),29  never values interpolated into the message string. Tint handler in dev.30- **Tests:** stdlib `testing` only, `t.Setenv` for env manipulation. No frameworks.31- **Formatting:** `golangci-lint fmt` (gofmt-compatible). Never hand-format.32- Prefer simple, stable, idiomatic Go and the standard library over clever33  abstractions or new dependencies. Justify any new dependency.34- The maintainer is learning Go — when using a non-obvious idiom, briefly explain35  it in your summary.3637## Commit conventions3839Single-line commits, `type: description` — lowercase, no scope, no period.40Types: `feat` `fix` `docs` `style` `perf` `test` `build` `ci` `chore` `revert`.4142VCS is jj (colocated with git).4344## Don'ts4546- Never commit, branch, or otherwise mutate jj/git state — the user handles VCS.47- Never edit `.env` (real secrets). `example.env` is the committed template; keep48  it in sync when adding config.49- Keep `CHANGELOG.md` updated under `[Unreleased]` — highlight/summary level only,50  not a list of every change.
CHANGELOG.mdadded +13 −0
@@ -0,0 +1,13 @@1# Changelog23All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),6and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).78## [Unreleased]910### Added1112- Env config with validation and defaults, structured logging13- Dev tooling: `just check` (format, lint, test)
env.goadded +94 −0
@@ -0,0 +1,94 @@1package main23import (4	"fmt"5	"log/slog"6	"os"7	"strconv"8	"strings"910	"github.com/joho/godotenv"11)1213// Environment identifies which deployment mode the server runs in.14type Environment string1516// The only values ENVIRONMENT may take; anything else fails parsing.17const (18	EnvDev  Environment = "dev"19	EnvTest Environment = "test"20	EnvProd Environment = "prod"21)2223// envVars is the validated application config, read once at startup.24type envVars struct {25	environment Environment26	port        int27}2829func (e envVars) Env() Environment {30	return e.environment31}3233func (e envVars) Port() int {34	return e.port35}3637// loadEnv loads a .env file into the process environment if one exists,38// then parses and validates the config. A missing .env is not an error.39func loadEnv() (envVars, error) {40	err := godotenv.Load()4142	if err != nil {43		slog.Warn("no .env file, relying on environment.", "error", err)44	}4546	config, err := parseEnv()47	if err != nil {48		return envVars{}, fmt.Errorf("parsing env: %w", err)49	}5051	return config, nil52}5354// parseEnv reads config from environment variables, applying defaults55// (ENVIRONMENT=dev, PORT=8080) and rejecting invalid values.56func parseEnv() (envVars, error) {57	// ENVIRONMENT - required, with default58	environment := strings.TrimSpace(os.Getenv("ENVIRONMENT"))5960	if environment == "" {61		environment = string(EnvDev)62	}6364	switch Environment(environment) {65	case EnvDev, EnvTest, EnvProd:66		// valid6768	default:69		return envVars{}, fmt.Errorf("invalid ENVIRONMENT %q: must be dev, test, or prod", environment)70	}7172	// PORT - required, with default73	portStr := os.Getenv("PORT")7475	if portStr == "" {76		portStr = "8080"77	}7879	port, err := strconv.Atoi(portStr)8081	if err != nil {82		return envVars{}, fmt.Errorf("invalid PORT %q: %w", portStr, err)83	}8485	if port < 1 || port > 65535 {86		return envVars{}, fmt.Errorf("invalid PORT %d: must be 1-65535", port)87	}8889	return envVars{90		environment: Environment(environment),91		port:        port,92	}, nil9394}
env_test.goadded +32 −0
@@ -0,0 +1,32 @@1package main23import "testing"45func TestParseEnvDefaults(t *testing.T) {6	// Blank out both vars so values from the host shell can't leak in.7	// t.Setenv restores the originals when the test ends.8	t.Setenv("ENVIRONMENT", "")9	t.Setenv("PORT", "")1011	got, err := parseEnv()1213	if err != nil {14		t.Fatalf("parseEnv() error = %v", err)15	}1617	if got.Env() != EnvDev {18		t.Errorf("Env() = %q, want %q", got.Env(), EnvDev)19	}2021	if got.Port() != 8080 {22		t.Errorf("Port() = %d, want 8080", got.Port())23	}2425}2627func TestParseEnvInvalidEnvironment(t *testing.T) {28	t.Setenv("ENVIRONMENT", "staging")29	if _, err := parseEnv(); err == nil {30		t.Fatal("expected error for invalid ENVIRONMENT, got nil")31	}32}
example.envadded +15 −0
@@ -0,0 +1,15 @@1# rename to .env and supply variables.23# environment4ENVIRONMENT=56# server7HOST=8PORT=910# database11DATABASE_URL=12DATABASE_MAX_CONN=1314# game15TICK_RATE=
go.mod +5 −0
@@ -1,3 +1,8 @@11module git.danieldaum.net/daniel/holonet2233go 1.26.545require (6	github.com/joho/godotenv v1.5.17	github.com/lmittmann/tint v1.2.08)
go.sumadded +4 −0
@@ -0,0 +1,4 @@1github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=2github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=3github.com/lmittmann/tint v1.2.0 h1:AogHRHy8HUJUnNJBHJlYa+fR4YY8mko2cnCp67xn9JY=4github.com/lmittmann/tint v1.2.0/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
justfile +11 −1
@@ -1,2 +1,12 @@11run:2    go run main.go2    go run .3test:4    go test ./...56# format everything, then static analysis7lint:8    golangci-lint fmt9    golangci-lint run1011# run before committing12check: lint test
main.go +31 −2
@@ -1,7 +1,36 @@11package main223import "fmt"3import (4	"log/slog"5	"os"67	"github.com/lmittmann/tint"8)910func initalize() {1112	devLogger := tint.NewTextHandler(os.Stderr, &tint.Options{Level: slog.LevelDebug})13	// jsonHandler := slog.NewJSONHandler(os.Stderr, nil)1415	aslog := slog.New(devLogger)1617	slog.SetDefault(aslog)1819}420521func main() {6	fmt.Println("Hello, World!")2223	config, err := loadEnv()2425	if err != nil {26		slog.Error("Invalid config.", "error", err)27		os.Exit(1)28	}2930	initalize()3132	slog.Info("starting Holonet Server", "env", config.Env(), "port", config.Port())33	slog.Warn("warning")34	slog.Error("error")35	slog.Debug("debug")736}
mise.toml +4 −2
@@ -1,3 +1,5 @@11[tools]2go = "latest"3golangci-lint = "latest"2air = "1.65"3go = "1.26"4golangci-lint = "2.12"5just = "1.56"