### Quick Start HTTP Server Source: https://goforj.dev/web A basic example demonstrating how to initialize an Echo adapter, define routes, and start an HTTP server. ```go package main import ( "fmt" "log" "net/http" "github.com/goforj/web" "github.com/goforj/web/adapter/echoweb" "github.com/goforj/web/webmiddleware" ) func main() { adapter := echoweb.New() router := adapter.Router() router.Use( webmiddleware.Recover(), webmiddleware.RequestID(), ) router.GET("/healthz", func(c web.Context) error { return c.Text(http.StatusOK, "ok") }) router.GET("/users/:id", func(c web.Context) error { id := c.Param("id") return c.JSON(http.StatusOK, map[string]any{ "id": id, "name": fmt.Sprintf("user-%s", id), }) }) log.Fatal(http.ListenAndServe(":8080", adapter)) } ``` -------------------------------- ### Install execx Source: https://goforj.dev/execx Use the go get command to add the library to your project. ```bash go get github.com/goforj/execx ``` -------------------------------- ### Quickstart with env Source: https://goforj.dev/env Demonstrates initializing the environment with env.Load() and accessing variables using typed getters like Get, GetBool, and GetDuration. ```go package main import ( "log" "time" "github.com/goforj/env/v2" ) func init() { if err := env.Load(); err != nil { log.Fatalf("load env: %v", err) } } func main() { addr := env.Get("ADDR", "127.0.0.1:8080") debug := env.GetBool("DEBUG", "false") timeout := env.GetDuration("HTTP_TIMEOUT", "5s") env.Dump(addr, debug, timeout) // #string "127.0.0.1:8080" // #bool false // #time.Duration 5s env.Dump("container?", env.IsContainer()) // #string "container?" // #bool false } ``` -------------------------------- ### Quick start metrics implementation Source: https://goforj.dev/metrics A complete example showing how to initialize a registry, register metrics, and expose them via an HTTP handler. ```go package main import ( "log" "net/http" "time" "github.com/goforj/metrics" ) func main() { // Own the registry explicitly so tests and multiple applications do not share metric state. registry := metrics.NewRegistry() // Register metrics once during startup, then retain these handles for inexpensive updates. requests := registry.MustCounter(metrics.Descriptor{ Name: "http.requests", Help: "Total HTTP requests served.", }) latency := registry.MustDurationHistogram(metrics.Descriptor{ Name: "http.request.duration", Help: "HTTP request duration.", }, metrics.DefaultDurationBounds()) http.Handle("/metrics", metrics.Handler(registry)) http.HandleFunc("/hello", func(response http.ResponseWriter, _ *http.Request) { start := time.Now() // A deferred observation records latency on every return path through the handler. defer latency.ObserveSince(start) requests.Inc() _, _ = response.Write([]byte("hello")) }) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Quick Start Request Examples Source: https://goforj.dev/web Example curl requests to verify the health check and user endpoints defined in the quick start. ```console $ curl -s http://localhost:8080/healthz ok $ curl -s http://localhost:8080/users/42 {"id":"42","name":"user-42"} ``` -------------------------------- ### Install Root Module Source: https://goforj.dev/storage Install the core storage module using go get. ```bash go get github.com/goforj/storage ``` -------------------------------- ### Install metrics library Source: https://goforj.dev/metrics Use the go get command to install the library. Requires Go 1.24 or newer. ```sh go get github.com/goforj/metrics ``` -------------------------------- ### Install env library Source: https://goforj.dev/env Use the go get command to add the library to your project. ```bash go get github.com/goforj/env/v2 ``` -------------------------------- ### Install queue library Source: https://goforj.dev/queue Use the go get command to add the queue library to your project. ```bash go get github.com/goforj/queue ``` -------------------------------- ### Install Optional Event Drivers with go get Source: https://goforj.dev/events List of import commands to install any of the optional distributed backend drivers. Install only the drivers you need to keep dependencies lean. ```bash go get github.com/goforj/events/driver/natsevents ``` ```bash go get github.com/goforj/events/driver/redisevents ``` ```bash go get github.com/goforj/events/driver/kafkaevents ``` ```bash go get github.com/goforj/events/driver/natsjetstreamevents ``` ```bash go get github.com/goforj/events/driver/gcppubsubevents ``` ```bash go get github.com/goforj/events/driver/snsevents ``` -------------------------------- ### Create scheduler with error handling using scheduler.NewWithError() Source: https://goforj.dev/scheduler Creates and starts a scheduler facade and returns setup errors. The example checks for an error and panics if one occurs, then defers stopping the scheduler. ```go s, err := scheduler.NewWithError() if err != nil { panic(err) } defer s.Stop() ``` -------------------------------- ### Install GoForj Mail Source: https://goforj.dev/mail Use the go get command to add the library to your project. ```bash go get github.com/goforj/mail ``` -------------------------------- ### Install the str library Source: https://goforj.dev/strings Use the go get command to add the library to your project. Requires Go 1.24 or newer. ```sh go get github.com/goforj/str/v2 ``` -------------------------------- ### Install and Initialize GoForj Source: https://goforj.dev/ Install the latest version of the GoForj CLI using Go and initialize a new project. ```bash $ go install github.com/goforj/goforj/cmd/forj@latest $ forj new ``` -------------------------------- ### Migrate and Start Application Source: https://goforj.dev/security/auth Execute database migrations and start the development server. ```bash forj migrate forj dev ``` -------------------------------- ### Install httpx via go get Source: https://goforj.dev/httpx Command to add the httpx library to your Go project. ```bash go get github.com/goforj/httpx/v2 ``` -------------------------------- ### Install godump with go get Source: https://goforj.dev/godump Install the godump package using the go get command. ```bash go get github.com/goforj/godump ``` -------------------------------- ### Install GoForj CLI Source: https://goforj.dev/getting-started/quickstart Install the GoForj CLI using go install and verify the installation with the help command. ```bash go install github.com/goforj/goforj/cmd/forj@latest forj --help ``` -------------------------------- ### Create and run a GoForj app Source: https://goforj.dev/ This example shows the interactive `forj new` command to create a new project, followed by `forj dev` to run it. The output shows the project being rendered, the build succeeding, and the development environment starting with various services. Finally, a health check is performed with `curl`. ```bash $ forj new Project » photodrop Starter kit » Vue Components » CLI, Docker, Mail, Auth, OAuth, Web API, Web UI, Metrics, Observability, Grafana, Database (MySQL), Scheduler, Jobs ✔ Project render complete (created: 736, skipped: 0) $ cd photodrop && forj dev ✔ 4/4 go build Built app in 2s · Running pre-dev setup [+] up 12/12 ✔ migrations complete (7) ✔ Dev ready → App: http://localhost:3000 → Lighthouse: http://localhost:3000/lighthouse → Swagger: http://localhost:3000/swagger → Mailpit (inbox): http://localhost:8025 → Grafana (admin / admin): http://localhost:13001 23:51:32.257 HTTP Starting HTTP server → addr=0.0.0.0:3000 23:51:32.256 Jobs Queue worker started → driver=redis · workers=30 23:51:32.256 Scheduler Scheduler started $ curl localhost:3000/-/health {"status":"ok"} ``` -------------------------------- ### Install collection package Source: https://goforj.dev/collection Use the go get command to add the package to your project. ```bash go get github.com/goforj/collection/v4 ``` -------------------------------- ### Installation Source: https://goforj.dev/godump Install the godump package using go get. ```APIDOC ## Installation ```bash go get github.com/goforj/godump ``` ``` -------------------------------- ### Install GoForj Web Source: https://goforj.dev/web Use the go get command to add the web package to your Go project. ```sh go get github.com/goforj/web ``` -------------------------------- ### Install GoForj Console Source: https://goforj.dev/console Use the go get command to add the library to your project. Requires Go 1.25 or newer. ```sh go get github.com/goforj/console ``` -------------------------------- ### Minimal Example Providers Source: https://goforj.dev/wire Example of defining types and a provider set for Wire. ```go // providers.go type Message string func ProvideMessage() Message { return "hello wire" } type Greeter struct { Msg Message } func NewGreeter(msg Message) *Greeter { return &Greeter{Msg: msg} } var GreeterSet = wire.NewSet( ProvideMessage, NewGreeter, ) ``` -------------------------------- ### Initialize MemoryStore with StoreConfig Source: https://goforj.dev/cache Example of using the root constructor with a configured StoreConfig. ```go store := cache.NewMemoryStoreWithConfig(ctx, cache.StoreConfig{ BaseConfig: cachecore.BaseConfig{ DefaultTTL: 5 * time.Minute, Prefix: "app", }, MemoryCleanupInterval: time.Minute, }) ``` -------------------------------- ### Install Frontend Dependencies Source: https://goforj.dev/frontend/vue-starter-kit Navigate to the frontend directory and install the required npm packages. ```bash cd cmd/app/frontend && npm install ``` -------------------------------- ### Create and start a scheduler with scheduler.New() Source: https://goforj.dev/scheduler Creates and starts a scheduler facade. Panics only if gocron scheduler construction fails. The example schedules a job every 15 seconds and defers stopping the scheduler. ```go s := scheduler.New() defer s.Stop() s.Every(15).Seconds().Do(func(context.Context) error { return nil }) ``` -------------------------------- ### Install Frontend Dependencies with npm Source: https://goforj.dev/developer-tools/forj-dev For npm-backed starter kits, new Projects generate this dependency setup task. The flags keep routine funding, audit, and warning noise out of a successful startup. Command output still streams when npm reports an error, and forj dev repeats the final output lines with the task failure. ```yaml dev: pre: - name: Install Frontend Dependencies cmd: cd cmd/app/frontend && npm install --no-audit --no-fund --loglevel=error ``` -------------------------------- ### Start the scheduler Source: https://goforj.dev/scheduler Starts the underlying scheduler instance. ```go s := scheduler.New() s.Start() ``` -------------------------------- ### Quick Start with OutputTrimmed Source: https://goforj.dev/execx Execute a command and retrieve the trimmed output. ```go out, _ := execx.Command("echo", "hello").OutputTrimmed() fmt.Println(out) // #string hello ``` -------------------------------- ### forj new: Start Project wizard Source: https://goforj.dev/frontend/react-starter-kit Starts the interactive Project wizard. Enable Web UI and choose React when prompted; leave the component library On for the full dashboard or Off for a smaller shell. The React kit requires Web UI. ```bash forj new ``` -------------------------------- ### Queue.Batch Example Source: https://goforj.dev/queue Creates a batch builder for fan-out workflow execution. ```go q, err := queue.NewSync() if err != nil { return } q.Register("emails:send", func(ctx context.Context, m queue.Message) error { return nil }) if err := q.StartWorkers(context.Background()); err != nil { return } defer q.Shutdown(context.Background()) _, _ = q.Batch( queue.NewJob("emails:send").Payload(map[string]any{"id": 1}), queue.NewJob("emails:send").Payload(map[string]any{"id": 2}), ).Name("send-emails").OnQueue("default").Dispatch(context.Background()) ``` -------------------------------- ### Install GoForj CLI Source: https://goforj.dev/ Install the GoForj CLI using `go install`. This command fetches the latest version of the `forj` command from the GitHub repository. ```bash go install github.com/goforj/goforj/cmd/forj@latest ``` -------------------------------- ### Quick Start with Console Helpers Source: https://goforj.dev/console Demonstrates basic console output using package-level helpers for semantic messages. ```go package main import "github.com/goforj/console" func main() { console.Action("Building application") // · Building application console.Infof("Environment: %s", "development") // · Environment: development console.Success("Application ready") // ✔ Application ready } ``` -------------------------------- ### Install events with go get Source: https://goforj.dev/events Install the events library using the go get command. Requires Go 1.24 or later for the root module. ```bash go get github.com/goforj/events ``` -------------------------------- ### Queue.Driver Example Source: https://goforj.dev/queue Reports the configured backend driver for the underlying queue runtime. ```go q, err := queue.NewSync() if err != nil { return } fmt.Println(q.Driver()) // Output: sync ``` -------------------------------- ### Configure Starter Kit in .goforj.yml Source: https://goforj.dev/getting-started/starter-kits Define the starter kit and its options in the project configuration file. ```yaml render: starter_kit: vue # vue, react, templ_htmx, or none starter_kit_options: component_library: false ``` -------------------------------- ### Starting and waiting for processes Source: https://goforj.dev/execx Uses Start to initiate a process and Wait to retrieve the result, allowing for manual process control. ```go proc := execx.Command("go", "env", "GOOS").Start() res, _ := proc.Wait() fmt.Println(res.ExitCode == 0) // #bool true ``` -------------------------------- ### Install crypt with go get Source: https://goforj.dev/crypt Install the crypt package with the Go module tool. ```bash go get github.com/goforj/crypt ``` -------------------------------- ### Quick start with str.Of Source: https://goforj.dev/strings Demonstrates chaining Trim, Headline, and String methods to transform a string. ```go package main import ( "fmt" "github.com/goforj/str/v2" ) func main() { result := str.Of(" welcome_to_go ").Trim().Headline().String() fmt.Println(result) // Welcome to Go } ``` -------------------------------- ### Create a new project with the Project wizard Source: https://goforj.dev/frontend/templ-htmx-starter-kit Run this command to start the Project wizard. The wizard asks whether the Project needs Web UI and offers templ + htmx as a starter-kit choice. ```bash forj new ``` -------------------------------- ### Quick Start with SMTP Source: https://goforj.dev/mail Initialize an SMTP driver and use the mailer to send a simple text message. ```go package main import ( "context" "log" "github.com/goforj/mail" "github.com/goforj/mail/mailsmtp" ) func main() { driver, err := mailsmtp.New(mailsmtp.Config{ Host: "smtp.example.com", Port: 587, Username: "smtp-user", Password: "smtp-password", }) if err != nil { log.Fatal(err) } mailer := mail.New( driver, mail.WithDefaultFrom("no-reply@example.com", "Example"), ) err = mailer.Message(). To("alice@example.com", "Alice"). Subject("Welcome"). Text("hello world"). Send(context.Background()) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### NewWithError Source: https://goforj.dev/scheduler Creates and starts a scheduler facade and returns setup errors. ```APIDOC ## NewWithError ### Description Creates and starts a scheduler facade and returns setup errors. ### Method NewWithError ### Signature func NewWithError() (*Scheduler, error) ### Example ```go s, err := scheduler.NewWithError() if err != nil { panic(err) } defer s.Stop() ``` ``` -------------------------------- ### Start the development loop Source: https://goforj.dev/frontend/templ-htmx-starter-kit Run this command to start the development loop. It coordinates the frontend asset build, templ generation, Go build, and App restart. A successful change replaces the running process; a failed change leaves the last successful process running. ```bash forj dev ``` -------------------------------- ### webprometheus.RunPushGatewayGatherer starts pushing metrics Source: https://goforj.dev/web Starts pushing collected metrics until the context finishes. The example verifies that an error is returned when using a background context with an empty config. ```go err := webprometheus.RunPushGatewayGatherer(context.Background(), webprometheus.PushGatewayConfig{}) fmt.Println(err != nil) // true ``` -------------------------------- ### Create an app with specific components and starter kits Source: https://goforj.dev/reference/make-commands Use flags to define components and starter kits for non-interactive app creation. ```bash forj make:app admin --components web-api,jobs forj make:app statuspage --components web-api,web-ui --starter-kit vue forj make:app statuspage --components web-api,web-ui --starter-kit vue --component-library off ``` -------------------------------- ### Start workers for an additional app with forj admin worker Source: https://goforj.dev/async/queues Starts workers for an additional app by prefixing the command with the app name. The app name is 'admin' in this example. ```bash forj admin worker ``` -------------------------------- ### Queue.Chain Example Source: https://goforj.dev/queue Creates a chain builder for sequential workflow execution. ```go q, err := queue.NewSync() if err != nil { return } q.Register("first", func(ctx context.Context, m queue.Message) error { return nil }) q.Register("second", func(ctx context.Context, m queue.Message) error { return nil }) if err := q.StartWorkers(context.Background()); err != nil { return } defer q.Shutdown(context.Background()) _, _ = q.Chain( queue.NewJob("first"), queue.NewJob("second"), ).OnQueue("default").Dispatch(context.Background()) ``` -------------------------------- ### Create a new App with a starter kit Source: https://goforj.dev/starter-kits Use the forj CLI to create a new App with a specified starter kit. Replace with the kit identifier (e.g., react, vue, templ_htmx, none). ```bash forj new my-app --starter-kit ``` -------------------------------- ### Kitchen Sink Chaining Example Source: https://goforj.dev/execx Demonstrates chaining multiple commands, setting environment variables, using context for timeouts, and handling stdout/stderr via callbacks. ```go // Run executes the command and returns the result and any error. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() res, err := execx. Command("printf", "hello\nworld\n"). Pipe("tr", "a-z", "A-Z"). Env("MODE=demo"). WithContext(ctx). OnStdout(func(line string) { fmt.Println("OUT:", line) }). OnStderr(func(line string) { fmt.Println("ERR:", line) }). Run() if !res.OK() { log.Fatalf("command failed: %v", err) } fmt.Printf("Stdout: %q\n", res.Stdout) fmt.Printf("Stderr: %q\n", res.Stderr) fmt.Printf("ExitCode: %d\n", res.ExitCode) fmt.Printf("Error: %v\n", res.Err) fmt.Printf("Duration: %v\n", res.Duration) // OUT: HELLO // OUT: WORLD // Stdout: "HELLO\nWORLD\n" // Stderr: "" // ExitCode: 0 // Error: // Duration: 10.123456ms ``` -------------------------------- ### Fluent schedule example (Go) Source: https://goforj.dev/async/scheduler Recommended shape: schedules should call domain-owned services, jobs, or command work. Example uses `s.Every(30).Seconds().Name("monitor:poll").Do(s.InspectTask("monitor:poll", s.monitorCheckJob.RunScheduledPoll))`. ```go s.Every(30).Seconds(). Name("monitor:poll"). Do(s.InspectTask("monitor:poll", s.monitorCheckJob.RunScheduledPoll)) ``` -------------------------------- ### Build and run app with all components Source: https://goforj.dev/ Creates a new project with all components, builds, and runs. Output shows scheduler started, queue worker with 30 workers, and HTTP listening on 0.0.0.0:3000. ```bash $ forj new # components · all of them $ forj build $ ls -lh bin/app -rwxr-xr-x 1 you staff … bin/app $ ./bin/app 23:51:32.256 Scheduler Scheduler started 23:51:32.256 Jobs Queue worker started → workers=30 23:51:32.257 HTTP Listening → addr=0.0.0.0:3000 ``` -------------------------------- ### Initialize Queue Drivers Source: https://goforj.dev/queue Demonstrates how to instantiate in-process backends using root constructors and external backends using specific driver-module constructors. ```go package main import ( "github.com/goforj/queue" "github.com/goforj/queue/driver/mysqlqueue" "github.com/goforj/queue/driver/natsqueue" "github.com/goforj/queue/driver/postgresqueue" "github.com/goforj/queue/driver/rabbitmqqueue" "github.com/goforj/queue/driver/redisqueue" "github.com/goforj/queue/driver/sqlitequeue" "github.com/goforj/queue/driver/sqsqueue" ) func main() { queue.NewSync() // in-process sync queue.NewWorkerpool() // in-process worker pool queue.NewNull() // drop-only / disabled mode sqlitequeue.New("file:queue.db?_busy_timeout=5000") // SQL durable queue (SQLite) mysqlqueue.New("user:pass@tcp(127.0.0.1:3306)/app") // SQL durable queue (MySQL) postgresqueue.New("postgres://user:pass@127.0.0.1:5432/app?sslmode=disable") // SQL durable queue (Postgres) redisqueue.New("127.0.0.1:6379") // Redis/Asynq natsqueue.New("nats://127.0.0.1:4222") // NATS sqsqueue.New("us-east-1") // SQS rabbitmqqueue.New("amqp://guest:guest@127.0.0.1:5672/") // RabbitMQ } ``` -------------------------------- ### Construct a root bus with events.New Source: https://goforj.dev/events Initializes a root bus using the specified driver configuration. ```go bus, _ := events.New(events.Config{Driver: "sync"}) fmt.Println(bus.Driver()) // Output: sync ``` -------------------------------- ### Client.Get method Source: https://goforj.dev/httpx Issues a GET request and decodes its response. The example defines a GetResponse struct and prints the URL and error status. ```go type GetResponse struct { URL string `json:"url"` } c := httpx.New() res, err := c.Get[GetResponse]("https://httpbin.org/get") fmt.Println(err == nil, res.URL) // true https://httpbin.org/get ``` -------------------------------- ### FakeQueue.Driver - Get active queue driver Source: https://goforj.dev/queue Creates a new fake queue and retrieves its driver. The driver is returned without any setup. ```go fake := queue.NewFake() driver := fake.Driver() ``` -------------------------------- ### Implement a deployment lifecycle recipe Source: https://goforj.dev/console Combines sections, key-value pairs, progress bars, and tables to create a structured deployment report. ```go console.Section("Deploy production") // ◇ Deploy production console.KeyValues( console.KV("Environment", "production"), console.KV("Region", "eu-west-1"), ) // Environment production // Region eu-west-1 progress := console.NewProgress(2, "Deploying services") if err := progress.Start(); err != nil { console.Error(err.Error()) return } // · Deploying services defer progress.Stop() progress.Step(1, "Deploying worker") progress.Complete("Services deployed") // ✔ Services deployed console.Table( []string{"Service", "State"}, [][]string{{"api", "ready"}, {"worker", "ready"}}, ) // ┌─────────┬───────┐ // │ Service │ State │ // ├─────────┼───────┤ // │ api │ ready │ // │ worker │ ready │ // └─────────┴───────┘ console.Success("Deployment complete") // ✔ Deployment complete ``` -------------------------------- ### Development tasks YAML shape Source: https://goforj.dev/reference/configuration Example of the dev task configuration with pre and down commands. The pre task installs frontend dependencies, and the down task stops containers. ```yaml dev: pre: - name: frontend dependencies cmd: cd cmd/app/frontend && npm install --no-audit --no-fund --loglevel=error down: - name: stop containers cmd: docker-compose down ``` -------------------------------- ### Manage a Loader Lifecycle Source: https://goforj.dev/console Shows how to initialize, start, update, and stop a loader, capturing the output to a buffer. ```go var output bytes.Buffer color := false animations := false unicode := true console.SetDefault(console.New(console.Config{ Stdout: &output, ColorEnabled: &color, UnicodeEnabled: &unicode, AnimationsEnabled: &animations, })) loader := console.NewLoader("Downloading modules") if err := loader.Start(); err != nil { console.Error(err.Error()) return } defer loader.Stop() loader.Update("Verifying modules") loader.Success("Modules ready") fmt.Print(output.String()) // · Downloading modules // ✔ Modules ready ``` -------------------------------- ### CORSWithConfig middleware usage Source: https://goforj.dev/web Returns CORS middleware with configuration using webmiddleware.CORSWithConfig. The example allows origins from https://app.example.com and methods GET, POST, PATCH. ```go router := echoweb.New().Router() router.Use(webmiddleware.CORSWithConfig(webmiddleware.CORSConfig{ AllowOrigins: []string{"https://app.example.com"}, AllowMethods: []string{"GET", "POST", "PATCH"}, })) router.GET("/api/healthz", func(c web.Context) error { return c.JSON(200, map[string]any{"ok": true}) }) ``` -------------------------------- ### ErrorBodyDump captures non-2xx/3xx responses Source: https://goforj.dev/web Captures response bodies for non-2xx and non-3xx responses, logging method, URI, and status. Example output: 'GET /reports/42 failed with 404'. ```go router := echoweb.New().Router() router.Use(webmiddleware.ErrorBodyDump(func(c web.Context, status int, body []byte) { log.Printf("%s %s failed with %d", c.Method(), c.URI(), status) // GET /reports/42 failed with 404 })) router.GET("/reports/:id", func(c web.Context) error { return c.Text(404, "report not found") }) ``` -------------------------------- ### echoweb.Server.Serve - Start and gracefully shut down server Source: https://goforj.dev/web Creates a server on a random port, cancels the context immediately, and prints whether Serve returns nil. Expected output: true. ```go server, _ := echoweb.NewServer(echoweb.ServerConfig{Addr: "127.0.0.1:0"}) ctx, cancel := context.WithCancel(context.Background()) cancel() fmt.Println(server.Serve(ctx) == nil) // true ``` -------------------------------- ### Initialize Cache Drivers Source: https://goforj.dev/cache Demonstrates how to instantiate various cache backends. Use root constructors for in-process backends and driver-module constructors for external backends. ```go package main import ( "context" "fmt" "time" "github.com/goforj/cache" "github.com/goforj/cache/cachecore" "github.com/goforj/cache/driver/dynamocache" "github.com/goforj/cache/driver/memcachedcache" "github.com/goforj/cache/driver/mysqlcache" "github.com/goforj/cache/driver/natscache" "github.com/goforj/cache/driver/postgrescache" "github.com/goforj/cache/driver/rediscache" "github.com/goforj/cache/driver/sqlitecache" ) func main() { ctx := context.Background() base := cachecore.BaseConfig{DefaultTTL: 5 * time.Minute, Prefix: "app"} cache.NewMemoryStore(ctx) // in-process memory cache.NewFileStore(ctx, "./cache-data") // local file-backed cache.NewNullStore(ctx) // disabled / drop-only // Redis (driver-owned connection config; no direct redis client required) redisStore := rediscache.New(rediscache.Config{BaseConfig: base, Addr: "127.0.0.1:6379"}) _ = redisStore // Memcached (one or more server addresses) memcachedStore := memcachedcache.New(memcachedcache.Config{ BaseConfig: base, Addresses: []string{"127.0.0.1:11211"}, }) _ = memcachedStore // NATS JetStream KV (inject a bucket from your NATS setup) var kv natscache.KeyValue // create via your NATS JetStream setup natsStore := natscache.New(natscache.Config{BaseConfig: base, KeyValue: kv}) _ = natsStore // DynamoDB (auto-creates client when Client is nil) dynamoStore, err := dynamocache.New(ctx, dynamocache.Config{ BaseConfig: base, Region: "us-east-1", Table: "cache_entries", }) fmt.Println(dynamoStore, err) // SQLite (via sqlcore) sqliteStore, err := sqlitecache.New(sqlitecache.Config{ BaseConfig: base, DSN: "file::memory:?cache=shared", Table: "cache_entries", }) fmt.Println(sqliteStore, err) // Postgres (via sqlcore) postgresStore, err := postgrescache.New(postgrescache.Config{ BaseConfig: base, DSN: "postgres://user:pass@127.0.0.1:5432/app?sslmode=disable", Table: "cache_entries", }) fmt.Println(postgresStore, err) // MySQL (via sqlcore) mysqlStore, err := mysqlcache.New(mysqlcache.Config{ BaseConfig: base, DSN: "user:pass@tcp(127.0.0.1:3306)/app?parseTime=true", Table: "cache_entries", }) fmt.Println(mysqlStore, err) } ``` -------------------------------- ### Get last scheduled job with Job() Source: https://goforj.dev/scheduler Returns the last scheduled gocron.Job instance, if available. The example schedules a job every second and prints whether the job is not nil, which outputs 'true'. ```go b := scheduler.New().EverySecond().Do(func(context.Context) error { return nil }) fmt.Println(b.Job() != nil) // Output: true ``` -------------------------------- ### Get cron expression with CronExpr() Source: https://goforj.dev/scheduler Returns the cron expression string configured for the job. The example creates a job with a daily schedule at 9 AM and prints the cron expression, which outputs '0 9 * * *'. ```go builder := scheduler.New().Cron("0 9 * * *") fmt.Println(builder.CronExpr()) // Output: 0 9 * * * ``` -------------------------------- ### ErrorBodyDumpWithConfig captures non-success response bodies Source: https://goforj.dev/web Use to log failed responses. The Skipper skips /healthz. The Handler logs method, URI, and status; example output: GET /reports/42 failed with 404. ```go router := echoweb.New().Router() router.Use(webmiddleware.ErrorBodyDumpWithConfig(webmiddleware.ErrorBodyDumpConfig{ Skipper: func(c web.Context) bool { return c.Path() == "/healthz" }, Handler: func(c web.Context, status int, body []byte) { log.Printf("%s %s failed with %d", c.Method(), c.URI(), status) // GET /reports/42 failed with 404 }, })) ``` -------------------------------- ### Create a test context with webtest.NewContext Source: https://goforj.dev/web Creates a new test context around the provided request/recorder pair. The example uses httptest.NewRequest to build a GET request, then webtest.NewContext with path parameters and query parameters. It prints the path parameter and query value, outputting '42 roles'. ```go req := httptest.NewRequest(http.MethodGet, "/users/42?expand=roles", nil) ctx := webtest.NewContext(req, nil, "/users/:id", webtest.PathParams{"id": "42"}) fmt.Println(ctx.Param("id"), ctx.Query("expand")) // 42 roles ``` -------------------------------- ### Get scheduling error with Error() Source: https://goforj.dev/scheduler Returns the error if any occurred during job scheduling. The example attempts to schedule a job with an invalid time format and prints the error, which outputs 'invalid DailyAt time format: invalid time format (expected HH:MM): "bad"'. ```go builder := scheduler.New().DailyAt("bad") fmt.Println(builder.Error()) // Output: invalid DailyAt time format: invalid time format (expected HH:MM): "bad" ``` -------------------------------- ### Start Source: https://goforj.dev/scheduler Start starts the underlying scheduler. ```APIDOC ## Start ### Description Start starts the underlying scheduler. ### Method Start ### Signature `func (s *Scheduler) Start()` ### Example ```go s := scheduler.New() s.Start() ``` ``` -------------------------------- ### NewFileStore constructor Source: https://goforj.dev/cache Create a filesystem-backed store using default settings. ```go ctx := context.Background() store := cache.NewFileStore(ctx, "/tmp/my-cache") fmt.Println(store.Driver()) // file ``` -------------------------------- ### NewFileStoreWithConfig constructor Source: https://goforj.dev/cache Create a filesystem-backed store with explicit configuration including encryption and compression. ```go ctx := context.Background() store := cache.NewFileStoreWithConfig(ctx, cache.StoreConfig{ BaseConfig: cachecore.BaseConfig{ EncryptionKey: []byte("01234567890123456789012345678901"), MaxValueBytes: 4096, Compression: cache.CompressionGzip, }, FileDir: "/tmp/my-cache", }) fmt.Println(store.Driver()) // file ``` -------------------------------- ### Construct a Google Pub/Sub driver with gcppubsubevents.New Source: https://goforj.dev/events Initializes a Google Pub/Sub-backed driver using the provided project ID and URI. ```go driver, _ := gcppubsubevents.New(context.Background(), gcppubsubevents.Config{ ProjectID: "events-project", URI: "127.0.0.1:8085", }) ``` -------------------------------- ### Custom Installation with forj atlas:install Source: https://goforj.dev/developer-tools/atlas Install specific agents and features by passing flags to the atlas:install command. ```bash forj atlas:install --agent codex --agent copilot --agent gemini --guidelines --skills --mcp ``` -------------------------------- ### Install and Verify Atlas Source: https://goforj.dev/developer-tools/atlas Install Atlas in an existing project and verify the installation status using the doctor command. ```bash forj atlas:install forj atlas:doctor ``` -------------------------------- ### Initialize Manager and Named Disks Source: https://goforj.dev/storage Demonstrates building a storage manager with multiple named disks using local and S3 drivers, then resolving and interacting with a specific disk. ```go package main import ( "log" "github.com/goforj/storage" "github.com/goforj/storage/driver/localstorage" "github.com/goforj/storage/driver/s3storage" ) func main() { // Build a manager with multiple named disks. mgr, err := storage.New(storage.Config{ Default: "assets", Disks: map[storage.DiskName]storage.DriverConfig{ "assets": localstorage.Config{ Root: "/tmp/storage", Prefix: "assets", }, "uploads": s3storage.Config{ Bucket: "app-uploads", Region: "us-east-1", Endpoint: "http://localhost:9000", AccessKeyID: "minioadmin", SecretAccessKey: "minioadmin", UsePathStyle: true, Prefix: "uploads", }, }, }) if err != nil { log.Fatal(err) } // Resolve a disk by name. disk, err := mgr.Disk("assets") if err != nil { log.Fatal(err) } // Put a file into the disk. if err := disk.Put("hello.txt", []byte("hello")); err != nil { log.Fatal(err) } // Read the file back. data, err := disk.Get("hello.txt") if err != nil { log.Fatal(err) } _ = data // []byte("hello") } ``` -------------------------------- ### Quick Start Cache Operations Source: https://goforj.dev/cache Demonstrates basic cache lifecycle operations including typed and string-based storage, and the remember pattern for lazy loading. ```go import ( "context" "fmt" "time" "github.com/goforj/cache" "github.com/goforj/cache/cachecore" "github.com/goforj/cache/driver/rediscache" ) func main() { ctx := context.Background() store := cache.NewMemoryStoreWithConfig(ctx, cache.StoreConfig{ BaseConfig: cachecore.BaseConfig{DefaultTTL: 5 * time.Minute}, }) c := cache.NewCache(store) type Profile struct { Name string `json:"name"` } // Typed lifecycle (generic helpers): set -> get -> delete _ = cache.Set(c, "user:42:profile", Profile{Name: "Ada"}, time.Minute) profile, ok, err := cache.Get[Profile](c, "user:42:profile") fmt.Println(err == nil, ok, profile.Name) // true true Ada _ = c.Delete("user:42:profile") // String lifecycle: set -> get -> delete _ = c.SetString("settings:mode", "dark", time.Minute) mode, ok, err := c.GetString("settings:mode") fmt.Println(err == nil, ok, mode) // true true dark _ = c.Delete("settings:mode") // Remember pattern. profile, err := cache.Remember[Profile](c, "user:42:profile", time.Minute, func() (Profile, error) { return Profile{Name: "Ada"}, nil }) fmt.Println(profile.Name) // Ada // Switch to Redis (dependency injection, no code changes below). store = rediscache.New(rediscache.Config{ BaseConfig: cachecore.BaseConfig{ Prefix: "app", DefaultTTL: 5 * time.Minute, }, Addr: "127.0.0.1:6379", }) c = cache.NewCache(store) } ``` -------------------------------- ### Construct a Kafka driver with kafkaevents.New Source: https://goforj.dev/events Initializes a Kafka-backed driver using the provided broker addresses. ```go driver, _ := kafkaevents.New(kafkaevents.Config{Brokers: []string{"127.0.0.1:9092"}}) ``` -------------------------------- ### Start scheduler with forj scheduler Source: https://goforj.dev/async/events-vs-queues Starts the scheduler for recurring work. ```bash forj scheduler ``` -------------------------------- ### Example Package Structure Source: https://goforj.dev/reference/make-commands Demonstrates organizing code by package ownership rather than by global directories. ```text internal/reports/ controller.go sync_cmd.go generate_job.go daily_schedule.go report_generated_event.go report_generated_subscriber.go report.go service.go ``` -------------------------------- ### Start workers with forj worker Source: https://goforj.dev/async/events-vs-queues Starts workers for processing jobs. ```bash forj worker ``` -------------------------------- ### Install cache library Source: https://goforj.dev/cache Command to install the core cache library. ```bash go get github.com/goforj/cache ``` -------------------------------- ### New example Source: https://goforj.dev/collection Creates a Slice from items and borrows their backing array. Shows length, indexing, and iteration with output. ```go values := collection.New([]int{10, 20, 30}) fmt.Println(len(values)) // 3 fmt.Println(values[1]) // 20 total := 0 for _, value := range values { total += value } fmt.Println(total) // 60 ``` -------------------------------- ### Install Wire CLI Source: https://goforj.dev/wire Command to install the Wire command-line tool. ```sh go install github.com/goforj/wire/cmd/wire@latest ``` -------------------------------- ### Quick Start with Workerpool Source: https://goforj.dev/queue Initialize a worker pool, register a job handler, and dispatch a job to the queue. ```go import ( "context" "fmt" "github.com/goforj/queue" ) func main() { q, _ := queue.NewWorkerpool( queue.WithWorkers(2), // optional; default: runtime.NumCPU() (min 1) ) type EmailPayload struct { To string `json:"to"` } q.Register("emails:send", func(ctx context.Context, m queue.Message) error { var payload EmailPayload _ = m.Bind(&payload) fmt.Println("send to", payload.To) return nil }) _ = q.StartWorkers(context.Background()) defer q.Shutdown(context.Background()) _, _ = q.Dispatch( queue.NewJob("emails:send"). Payload(EmailPayload{To: "user@example.com"}), ) } ``` -------------------------------- ### Initialize MemoStore Source: https://goforj.dev/cache Wrap a store with NewMemoStore to enable in-process read memoization. ```go memoStore := cache.NewMemoStore(store) memoRepo := cache.NewCache(memoStore) ``` -------------------------------- ### Example HTTP deployment configuration Source: https://goforj.dev/operations/deployment-basics A sample set of environment variables for an HTTP deployment, including network settings and secret placeholders. ```text APP_ENV=production APP_DEBUG=false APP_URL=https://api.example.com API_HTTP_HOST=0.0.0.0 API_HTTP_PORT=3000 APP_SHUTDOWN_TIMEOUT=30s QUEUE_SHUTDOWN_TIMEOUT=30s APP_DIAG_TOKEN= ``` -------------------------------- ### Install Driver Modules Source: https://goforj.dev/storage Install specific storage driver modules as needed for your application. ```bash go get github.com/goforj/storage/driver/localstorage go get github.com/goforj/storage/driver/memorystorage go get github.com/goforj/storage/driver/redisstorage go get github.com/goforj/storage/driver/ftpstorage go get github.com/goforj/storage/driver/sftpstorage go get github.com/goforj/storage/driver/s3storage go get github.com/goforj/storage/driver/gcsstorage go get github.com/goforj/storage/driver/dropboxstorage go get github.com/goforj/storage/driver/rclonestorage ``` -------------------------------- ### Install cache drivers Source: https://goforj.dev/cache Commands to install specific optional cache backend drivers. ```bash go get github.com/goforj/cache/driver/rediscache go get github.com/goforj/cache/driver/memcachedcache go get github.com/goforj/cache/driver/natscache go get github.com/goforj/cache/driver/dynamocache go get github.com/goforj/cache/driver/sqlitecache go get github.com/goforj/cache/driver/postgrescache go get github.com/goforj/cache/driver/mysqlcache ``` -------------------------------- ### Configure Startup and Shutdown Tasks with dev.pre and dev.down Source: https://goforj.dev/developer-tools/forj-dev Project setup and teardown remain separate from watcher configuration. Startup first runs configured App bootstrap builds, then dev.pre, database setup, auto-migration, and generated tasks. On interrupt, GoForj stops watcher processes and runs down tasks when dev.down_on_exit is enabled. ```yaml dev: pre: - name: Run Docker Compose cmd: docker-compose up -d down: - name: Docker Compose Down cmd: docker-compose down auto_migrate: true down_on_exit: true ``` -------------------------------- ### Up migration starter (sqlite) Source: https://goforj.dev/data/migrations Starter content for the up migration file. Replace the comment with the forward SQL. ```sql -- Up migration (sqlite) ``` -------------------------------- ### Minimal Example Injector Source: https://goforj.dev/wire The injector stub for the minimal example, requiring the wireinject build tag. ```go // wire.go //go:build wireinject func InitializeGreeter() *Greeter { wire.Build(GreeterSet) return nil } ``` -------------------------------- ### Initialize and use Progress Source: https://goforj.dev/console Demonstrates creating a progress display with console.NewProgress and updating it using Add and Complete. ```go animations := false color := false unicode := true console.SetDefault(console.New(console.Config{ AnimationsEnabled: &animations, ColorEnabled: &color, UnicodeEnabled: &unicode, })) var progress *console.Progress = console.NewProgress(2, "Deploying services") if err := progress.Start(); err != nil { panic(err) } // · Deploying services progress.Add(2) progress.Complete("Services deployed") // ✔ Services deployed ``` -------------------------------- ### Configure Middleware with queue.WithMiddleware Source: https://goforj.dev/queue Demonstrates applying audit logging, maintenance mode skipping, and error handling policies to a queue instance. ```go var errValidation = errors.New("validation failed") maintenanceMode := false audit := queue.MiddlewareFunc(func(ctx context.Context, m queue.Message, next queue.Next) error { log.Printf("start job=%s", m.JobType) err := next(ctx, m) log.Printf("done job=%s err=%v", m.JobType, err) return err }) skipMaintenance := queue.SkipWhen{ Predicate: func(context.Context, queue.Message) bool { return maintenanceMode }, } fatalValidation := queue.FailOnError{ When: func(err error) bool { return errors.Is(err, errValidation) }, } q, _ := queue.New( queue.Config{Driver: queue.DriverWorkerpool}, queue.WithMiddleware(audit, skipMaintenance, fatalValidation), ) _ = q ``` -------------------------------- ### Start scheduler for additional app Source: https://goforj.dev/async/events-vs-queues Starts the scheduler for an additional app, prefixing the command with the app name. ```bash forj admin scheduler ``` -------------------------------- ### Example Skill Markdown Source: https://goforj.dev/developer-tools/atlas An example of a project-owned skill file defining rules for refund review workflows. ```markdown # Refund Review Rules Use this skill when changing staff refund review, payment adjustment, or order-dispute workflows. Rules: - Keep payment provider calls behind `internal/refunds.PaymentGateway`. - Use `forj admin make:*` for generated staff operations entry points. - Run `forj admin test:refund-review` before marking refund-review work done. - Do not add direct provider SDK calls inside HTTP controllers. ``` -------------------------------- ### Configure Events Source: https://goforj.dev/queue Set up lifecycle hooks and observability. ```go q, _ := queue.New( queue.Config{Driver: queue.DriverWorkerpool}, queue.WithObserver(queue.NewStatsCollector()), ) ``` -------------------------------- ### Initialize Console with New Source: https://goforj.dev/console Constructs a new Console instance, which is safe for concurrent message writes. ```go var commandConsole *console.Console = console.New(console.Config{Width: 120}) fmt.Println(commandConsole.Width()) // 120 ``` -------------------------------- ### Install cache-backed Redis locker dependencies Source: https://goforj.dev/scheduler Install these packages if you intend to use a cache-backed Redis locker for distributed locking. ```bash go get github.com/goforj/cache go get github.com/goforj/cache/driver/rediscache go get github.com/redis/go-redis/v9 ``` -------------------------------- ### Start Scheduler Process Source: https://goforj.dev/async/scheduler Run the scheduler binary to initiate the runtime, ensuring it is supervised for proper startup and shutdown sequences. ```bash ./bin/app scheduler ```