gokart

package module
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 10 Imported by: 0

README

GoKart

GoKart logo

GoKart is a modular Go toolkit for recurring infrastructure setup, safe defaults, and user-owned generated code. Its enforceable boundary is defined in PHILOSOPHY.md.

go install github.com/dotcommander/gokart/cmd/gokart@v0.12.0
gokart new myapp --db sqlite --example
cd myapp
go run ./cmd greet --name World

Packages

  • gokart: typed configuration, platform config directories, and JSON state persistence.
  • gokart/cli: Cobra application construction for established ecosystem-style consumers plus process-stream presentation helpers. Focused generated CLIs use Kong directly.
  • gokart/web: chi router/server construction, JSON responses, bounded binding, and validation.
  • gokart/postgres: pgx pool setup and transaction helpers.
  • gokart/sqlite: zero-CGO SQLite setup and operations.
  • gokart/migrate: goose migrations.
  • gokart/cache: Redis construction, prefixes, JSON operations, and Remember.
  • gokart/logger: log/slog setup.

All modules isolate their dependencies. Constructors expose real upstream types or an explicit Client escape hatch.

Generator

gokart new creates ordinary Go code. Plain, example, local, and global CLIs default to a flat main.go; selecting an integration chooses the structured layout automatically. Use --structured when you want the multi-package layout without an integration.

gokart new mycli
gokart new mycli --structured
gokart new mycli --structured --global
gokart new service --db postgres --ai --redis
gokart add sqlite --dry-run

Global scaffolds include a manifest, but gokart add supports structured projects only. Choose --structured --global when you want platform-global configuration and later integration updates.

Dependencies are pinned for deterministic generation. PostgreSQL uses postgres.Open, SQLite uses sqlite.Open, Redis uses cache.Open, and AI uses the official OpenAI SDK directly.

See the generator reference and documentation index.

v0.11 migration

Removed surface Replacement
ai.NewOpenAIClient(opts...) openai.NewClient(opts...)
ai.NewOpenAIClientWithKey(key) openai.NewClient(option.WithAPIKey(key))
fs.ConfigDir / fs.EnsureConfigDir gokart.ConfigDir / gokart.EnsureConfigDir
fs.WriteFile / fs.ReadOrCreate Standard library; no GoKart replacement
GetString, GetInt, GetFloat, GetBool Typed configuration parsing or caller-owned assertions
Cache command mirrors c.Client().Command(ctx, c.Key(key), ...)
cli.Fatal, cli.FatalErr, cli.Must Return errors; main owns os.Exit
CLI writer overrides Cobra SetOut / SetErr and command writers
Removed web helpers Standard library or the named upstream package directly; see web/README.md

No deprecated aliases or forwarding modules are retained. Historical v0.10.3 tags are the compatibility path.

Removed identifiers

Use this searchable inventory when migrating:

  • Root getters: GetString, GetInt, GetFloat, GetBool.
  • Cache commands: Get, Set, Delete, Exists, Expire, TTL, Incr, IncrBy, SetNX, HGet, HSet, HGetAll, HDel, HIncrBy, ZAdd, ZRange, ZRangeByScore, ZScore, ZRem, ZCard, SAdd, SRem, SMembers, SIsMember, LPush, RPush, LRange, LPop, RPop, Decr, and DecrBy. Call the corresponding go-redis method through Client, applying Key to every logical key.
  • CLI process control and writers: Fatal, FatalErr, Must, SetOutput, SetErrOutput, Output, and ErrOutput.
  • Web assets and auth: NewAssets, AssetConfig, Assets, Assets.Path, Assets.Handler, APIKeyAuth, and BearerAuth.
  • Web CSRF and flash: CSRFProtect, CSRFProtectWithOrigins, SetFlash, GetFlash, FlashFromContext, FlashMiddleware, FlashLevel, FlashMessage, FlashSuccess, FlashError, FlashWarning, and FlashInfo.
  • Web health and clients: HealthHandler, ReadyHandler, HealthCheck, HealthFunc, NewHTTPClient, NewStandardClient, and HTTPConfig.
  • Web negotiation and pagination: WantsJSON, IsHTMX, Negotiate, NegotiateStatus, ParsePage, ParsePageWithConfig, NewPagedResponse, Page, PageConfig, and PagedResponse.
  • Web rate limiting: RateLimit, RateLimitWithKey, RateLimitWithEviction, WithTTL, WithSweepInterval, RateLimiter, RateLimiter.Middleware, RateLimiter.LimiterCount, RateLimiter.Stop, and RateLimitOption.
  • Web templ adapters: Render, RenderCtx, RenderWithStatus, TemplHandler, TemplHandlerFunc, and TemplHandlerFuncE.

Verification

Go 1.26 or later is required.

just verify

License

MIT

Documentation

Overview

Package gokart provides focused configuration and state setup for Go applications.

The project-wide admission test and ownership boundary are defined in PHILOSOPHY.md at the repository root. Submodules are independently importable and expose standard-library or upstream types wherever practical.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigDir added in v0.11.0

func ConfigDir(appName string) (string, error)

ConfigDir returns the app's platform-specific configuration directory, creating it when necessary.

func EnsureConfigDir added in v0.11.0

func EnsureConfigDir(appName string, defaultContent []byte) error

EnsureConfigDir creates the app's configuration directory and initializes config.yaml with defaultContent when it does not already exist.

func LoadConfig

func LoadConfig[T any](paths ...string) (T, error)

LoadConfig loads configuration from the first available file path into type T.

Features:

  • Supports multiple config paths (first found wins)
  • Automatic environment variable binding
  • DOT to UNDERSCORE env key mapping (e.g., db.host → DB_HOST)

Supported formats: JSON, YAML, TOML, HCL, envfile, Java properties

Example:

type Config struct {
    DB struct {
        Host string `mapstructure:"host"`
        Port int    `mapstructure:"port"`
    } `mapstructure:"db"`
}
cfg, err := gokart.LoadConfig[Config]("config.yaml", "config.json")

func LoadConfigWithDefaults

func LoadConfigWithDefaults[T any](defaults T, paths ...string) (T, error)

LoadConfigWithDefaults loads configuration with default values pre-populated.

The defaults parameter provides fallback values that will be overridden by values from config files or environment variables.

Example:

defaults := Config{
    DB: struct{Host string; Port int}{
        Host: "localhost",
        Port: 5432,
    },
}
cfg, err := gokart.LoadConfigWithDefaults(defaults, "config.yaml")

func LoadState

func LoadState[T any](appName, filename string) (T, error)

LoadState loads typed state from the platform user config directory.

Returns zero value and os.ErrNotExist if the file doesn't exist. This allows callers to distinguish between missing file and parse errors.

Example:

state, err := gokart.LoadState[AppState]("myapp", "state.json")
if errors.Is(err, os.ErrNotExist) {
    // First run, use defaults
    state = AppState{WindowSize: 800}
} else if err != nil {
    return err
}

func MustParseConfig added in v0.10.2

func MustParseConfig[T any](config map[string]any) T

MustParseConfig is ParseConfig for initialization paths where invalid configuration is a programmer error.

func ParseConfig added in v0.10.2

func ParseConfig[T any](config map[string]any) (T, error)

ParseConfig converts a config map to a typed struct. The config tag names fields, default supplies missing scalar values, and required marks fields that must be present after defaults are applied. Anonymous structs are flattened.

func SaveState

func SaveState[T any](appName, filename string, data T) error

SaveState saves typed state under the platform user config directory.

The file is written as indented JSON for human readability. Directory is created with 0755, files with 0600 permissions.

Example:

type AppState struct {
    LastOpened string `json:"last_opened"`
    WindowSize int    `json:"window_size"`
}
err := gokart.SaveState("myapp", "state.json", AppState{
    LastOpened: "/path/to/file",
    WindowSize: 1024,
})

func StatePath

func StatePath(appName, filename string) string

StatePath returns the full path to a state file.

Returns empty string if the user config directory cannot be determined.

Example:

path := gokart.StatePath("myapp", "state.json")
// macOS: ~/Library/Application Support/myapp/state.json
// Linux: ~/.config/myapp/state.json

Types

This section is empty.

Directories

Path Synopsis
cache module
cli module
cmd
gokart module
internal
logger module
migrate module
postgres module
sqlite module
web module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL