agentleFS
weedboxweedbox/skills/common-modules/SKILL.md

common-modules

Skill1 starsChanged 4 months agoApache-2.0View on GitHub

Priority: HIGH — Self-contained reference. This file and its sub-files (modules/*.md) contain ALL necessary code examples and configuration guides. DO NOT fetch source code from GitHub. Reference guide for weedbox/common-modules - reusable modules for weedbox applications. Use when: integrating configs, logger, HTTP server (Gin), database (PostgreSQL, SQLite, GORM), NATS messaging (JetStream), Redis cache, mailer (SMTP), job scheduler (cron, interval, one-shot), or Swagger API docs into weedbox projects. Covers: configuration management, structured logging, health checks, database connectors, message queues, caching, email sending, scheduled jobs, API documentation. Keywords: common-modules, weedbox module, configs, logger, http_server, database, postgres, sqlite, nats, jetstream, redis, mailer, healthcheck, daemon, swagger, openapi, Uber Fx modules, lifecycle, PostStart, PreStop, post-start hook, pre-stop hook, after all modules start, run after startup, before shutdown, startup task, warmup, drain, scheduler, job scheduler, cron job, scheduled task, recurring job, interval schedule, DailySchedule, ScheduleBuilder, JetStream scheduled delivery, EnsureJob, SubmitJob, HTTP, REST, API server, Go database, message queue, GORM, Gin, Viper, TOML, CORS, swag CLI, swag init, parseDependency, parseDependencyLevel, parseDepth, LeftDelim, RightDelim, swag version mismatch, scalar UI, paths empty, swag v1.8.12, swag v1.16, swag --dir, ParseComment error, antlr4-go, cannot find type definition, external module docs.

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When referencing common-modules in Params, you MUST use interface types:

    line 90
  2. Very specific:

    When a single connector / module is loaded, inject it without a name tag:

    line 108
  3. Very specific:

    Exception — multi-load DatabaseConnector: when you load sqlite_connector.Module("cache") and postgres_connector.Module("main") into the …

    line 120
  4. Very specific:

    Use fx.New().Run() to start the application (not weedbox.Run())

    line 150
  5. Distinctive:

    All modules support configuration via:

    line 220

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Common Modules Reference

This skill provides detailed usage instructions for all modules in github.com/weedbox/common-modules.

Module Index

Core

ModuleDescriptionDocumentation
configsConfiguration management with Viper (TOML, environment variables)configs.md
loggerZap-based structured logging with debug modelogger.md
daemonService lifecycle management with ready/health statusdaemon.md
lifecyclePostStart/PreStop phases — hooks after all modules start / before any module stopslifecycle.md

HTTP

ModuleDescriptionDocumentation
http_serverGin-based HTTP server with CORS and static file/SPA supporthttp_server.md
healthcheck_apisKubernetes-compatible health check endpointshealthcheck_apis.md
swaggerSwagger/OpenAPI documentation with Scalar UIswagger.md

Database

ModuleDescriptionDocumentation
databaseDatabase interface abstractiondatabase.md
postgres_connectorPostgreSQL connector with GORMpostgres_connector.md
sqlite_connectorSQLite connector with GORMsqlite_connector.md

Messaging

ModuleDescriptionDocumentation
nats_connectorNATS client with JetStream and work queuenats_connector.md
nats_jetstream_serverEmbedded NATS JetStream servernats_jetstream_server.md

Scheduling

ModuleDescriptionDocumentation
schedulerJob scheduler with GORM (single-node), PostgreSQL (multi-instance, claim-based), or NATS JetStream backendscheduler.md

Cache

ModuleDescriptionDocumentation
redis_connectorRedis client with connection poolingredis_connector.md

Utilities

ModuleDescriptionDocumentation
mailerSMTP email sending with TLS supportmailer.md

⚠️ Critical Rules

Source of Truth — Do NOT Fetch from GitHub

This file and its sub-files (modules/*.md) are the complete reference for weedbox/common-modules. They contain all necessary code examples, configuration guides, and dependency injection patterns. DO NOT browse github.com/weedbox/common-modules to look up source code.

Use Interface Types, NOT Concrete Implementations

When referencing common-modules in Params, you MUST use interface types:

// ✅ Correct - use interface
type Params struct {
    weedbox.Params
    Database database.DatabaseConnector  // interface type
}

// ❌ Wrong - using concrete implementation
type Params struct {
    weedbox.Params
    Database *sqlite_connector.SQLiteConnector  // concrete type
}

Common-modules Do NOT Need name Tag (Single-Load Default)

When a single connector / module is loaded, inject it without a name tag:

// ✅ Correct
Database   database.DatabaseConnector
HTTPServer *http_server.HTTPServer

// ❌ Wrong - do not add a name tag for single-load modules
Database   database.DatabaseConnector `name:"database"`
HTTPServer *http_server.HTTPServer    `name:"http_server"`

Exception — multi-load DatabaseConnector: when you load sqlite_connector.Module("cache") and postgres_connector.Module("main") into the same fx.App, each registers itself as name:"<scope>" and consumers MUST disambiguate with the name tag:

type Params struct {
    fx.In
    Cache database.DatabaseConnector `name:"cache"` // sqlite
    Main  database.DatabaseConnector `name:"main"`  // postgres
}

The first connector loaded in the process also claims the unnamed default slot, so existing single-load code keeps working. See database.md for full details and the fxmodule.ResetClaim test caveat.

Pick Multi-Instance-Safe Backends for Production

Production runs multiple replicas. Two modules in this library are single-node only: scheduler mode = "gorm" (every replica fires every job) and the embedded nats_jetstream_server (development / single-node tool). With more than one replica, use scheduler mode = "postgres" or "nats", an external NATS cluster via nats_connector, postgres_connector instead of sqlite_connector, and redis_connector for cross-instance shared state. Full decision table: root skill § Design for Multi-Instance Deployment by Default.


Quick Start

Installation

go get github.com/weedbox/common-modules

Basic Application Setup

Important:

  • configs.NewConfig() automatically reads config.toml from current directory or ./configs/
  • Use fx.New().Run() to start the application (not weedbox.Run())
package main

import (
    "os"

    "github.com/spf13/cobra"
    "github.com/weedbox/common-modules/configs"
    "github.com/weedbox/common-modules/daemon"
    "github.com/weedbox/common-modules/http_server"
    "github.com/weedbox/common-modules/logger"
    "go.uber.org/fx"
)

var config *configs.Config

func main() {
    rootCmd := &cobra.Command{
        Use: "myapp",
        RunE: func(cmd *cobra.Command, args []string) error {
            modules, _ := initModules()
            app := fx.New(modules...)
            app.Run()
            return nil
        },
    }

    // Initialize config - automatically reads config.toml
    config = configs.NewConfig("MYAPP")

    if err := rootCmd.Execute(); err != nil {
        os.Exit(1)
    }
}

func initModules() ([]fx.Option, error) {
    return []fx.Option{
        // Phase 1: Preload
        fx.Supply(config),
        logger.Module(),

        // Phase 2: Load
        http_server.Module("http_server"),

        // Phase 3: After (daemon must be last)
        daemon.Module("daemon"),
    }, nil
}

Module Loading Order

Modules should be loaded in three phases:

PhasePurposeModules
1. PreloadConfiguration, logging, embedded infrastructureconfigs, logger, nats_jetstream_server (must be running before nats_connector connects)
2. LoadApplication moduleshttp_server, swagger, healthcheck_apis, database, nats_connector, scheduler, redis_connector, mailer, custom modules
3. AfterLifecycle managementlifecycle (optional, before daemon), daemon (must be last)

Important: The daemon module must be placed last because it marks the service as ready after all other modules initialize. When post-start / pre-stop hooks are needed, place lifecycle right before daemon so readiness flips only after the PostStart phase completes — see lifecycle.md.


Configuration

All modules support configuration via:

  1. TOML files - Structured configuration
  2. Environment variables - Override settings per environment

TOML Example

[http_server]
host = "0.0.0.0"
port = 8080
mode = "release"

[database]
host = "localhost"
port = 5432
dbname = "myapp"
user = "postgres"
password = "secret"

[nats]
host = "nats://localhost:4222"

[redis]
host = "localhost"
port = 6379

[mailer]
host = "smtp.gmail.com"
port = 587
tls = true

[swagger]
enabled = true
base_path = "/swagger"
title = "API Reference"

Environment Variables

Environment variables use the prefix defined in configs.NewConfig():

# With prefix "MYAPP"
export MYAPP_HTTP_SERVER_PORT=8080
export MYAPP_DATABASE_HOST=localhost
export MYAPP_DATABASE_PASSWORD=secret

Dependency Injection

Modules are injected via Uber Fx parameter structs:

type Params struct {
    fx.In
    Logger      *zap.Logger
    HTTPServer  *http_server.HTTPServer
    Database    database.DatabaseConnector
    NATS        *nats_connector.NATSConnector
    Redis       *redis_connector.RedisConnector
    Mailer      *mailer.Mailer
    Swagger     *swagger.Swagger
}

Related Skills

  • project-dev - Project structure and application setup
  • module-dev - Custom module development
  • user-modules - User management, authentication, and RBAC modules

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.