template/cmd/app/main.go

70 lines
1.7 KiB
Go

// main is the composition root for the application.
// It parses config, wires dependencies into an app struct, and delegates.
// Implementation details lives in internal/; cmd/ should be kept thin by
// deliberately operating only with high level concepts.
package main
import (
"fmt"
"os"
"path/filepath"
"gitea.djmil.dev/go/template/internal/greeter"
"gitea.djmil.dev/go/template/pkg/logger"
"gitea.djmil.dev/go/template/pkg/result"
)
// app holds all wired dependencies for the lifetime of the process.
type app struct {
cfg *Config
log *logger.Logger
greeter *greeter.Service
}
func newApp(cfg *Config) *app {
var log *logger.Logger
if cfg.App.Env == "dev" {
log = logger.NewDevelopment()
} else {
log = logger.New(cfg.Logger.Level).Expect("create logger") // might fail dramatically
}
return &app{
cfg: cfg,
log: log,
greeter: greeter.New(log),
}
}
func main() {
conf := parseArgs()
app := newApp(conf)
app.log.WithFields(map[string]any{
"app": filepath.Base(os.Args[0]),
"env": conf.App.Env,
}).Info("starting up")
if err := result.Run(app.run); err != nil {
fmt.Fprintf(os.Stderr, "[failed] %v\n", err)
if stack := result.StackTrace(err); stack != "" {
fmt.Fprintf(os.Stderr, "%s\n", stack)
}
os.Exit(1)
}
}
func (a *app) run() {
// High level business logic goes here
a.showGreeting(a.cfg.Greeter.Name)
// Human readable messages.
// Use logs for presenting technical data in machine friendly format.
fmt.Printf("TODO: implement listening on port %d\n", a.cfg.App.Port)
}
func (a *app) showGreeting(name string) {
msg := a.greeter.Greet(name).Expect("greeting")
a.log.WithField("message", msg).Info("greeting complete")
fmt.Println(msg)
}