← 返回 Skills 市场
anderskev

Go Architect

作者 Kevin Anderson · GitHub ↗ · v2.3.1 · MIT-0
cross-platform ✓ 安全检测通过
161
总下载
0
收藏
1
当前安装
2
版本数
在 OpenClaw 中安装
/install go-architect
功能描述
Go application architecture with net/http 1.22+ routing, project structure patterns, graceful shutdown, and dependency injection. Use when building Go web se...
使用说明 (SKILL.md)

Lead Go Architect

Quick Reference

Topic Reference
Flat vs modular project layout, migration signals references/project-structure.md
Graceful shutdown with signal handling references/graceful-shutdown.md
Dependency injection patterns, testing seams references/dependency-injection.md

Core Principles

  1. Standard library first -- Use net/http and the Go 1.22+ enhanced ServeMux for routing. Only reach for a framework (chi, echo, gin) when you have a concrete need the stdlib cannot satisfy (e.g., complex middleware chains, regex routes).
  2. Dependency injection over globals -- Pass databases, loggers, and services through struct fields and constructors, never package-level var.
  3. Explicit over magic -- No init() side effects, no framework auto-wiring. main.go is the composition root where everything is assembled visibly.
  4. Small interfaces, big structs -- Define interfaces at the consumer, keep them narrow (1-3 methods). Concrete types carry the implementation.

Hard gates

Use this sequence when implementing or reviewing work that claims to follow this skill. Do not skip ahead; each step has a pass condition you can answer with tooling or a concrete file path.

  1. Toolchain vs APIs — If the code uses Go 1.22+ ServeMux features (method+path patterns like "GET /x/{id}", r.PathValue, or {path...}): run go version and pass only if the reported toolchain is go1.22+. If the project must stay on an older Go, pass only by not using those APIs (use a compatible router or older patterns) and say so in the review or PR.
  2. Composition rootPass when main.go or cmd/.../main.go visibly constructs the server and injects shared dependencies (DB, logger, config). Fail if shared dependencies are wired in init() or package-level var instead of explicit construction in main (or a run() called from main).
  3. Production HTTP shutdown — For a long-lived HTTP service, pass only if shutdown uses http.Server.Shutdown with a bounded context (e.g. context.WithTimeout) after waiting on signal.NotifyContext (or equivalent). Cite the file path when reporting; see references/graceful-shutdown.md for the full pattern.
  4. No env/globals in handlersPass when handlers and domain code take dependencies via structs/arguments. Fail if handlers read os.Getenv for secrets or use package-level var for DB/clients (loading env in main or a dedicated config package is fine).

Go 1.22+ Enhanced Routing

Go 1.22 upgraded http.ServeMux with method-based routing and path parameters, eliminating the most common reason for third-party routers.

Method-Based Routing and Path Parameters

mux := http.NewServeMux()
mux.HandleFunc("GET /api/users", s.handleListUsers)
mux.HandleFunc("GET /api/users/{id}", s.handleGetUser)
mux.HandleFunc("POST /api/users", s.handleCreateUser)
mux.HandleFunc("DELETE /api/users/{id}", s.handleDeleteUser)

Extracting Path Parameters

func (s *Server) handleGetUser(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")
    if id == "" {
        http.Error(w, "missing id", http.StatusBadRequest)
        return
    }

    user, err := s.users.GetUser(r.Context(), id)
    if err != nil {
        s.logger.Error("getting user", "err", err, "id", id)
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

Wildcard and Exact Match

// Exact match on trailing slash -- serves /api/files/ only
mux.HandleFunc("GET /api/files/", s.handleListFiles)

// Wildcard to end of path -- /api/files/path/to/doc.txt
mux.HandleFunc("GET /api/files/{path...}", s.handleGetFile)

Routing Precedence

The new ServeMux uses most-specific-wins precedence:

  • GET /api/users/{id} is more specific than GET /api/users/
  • GET /api/users/me is more specific than GET /api/users/{id}
  • Method routes take precedence over method-less routes

Server Struct Pattern

The Server struct is the central dependency container for your application. It holds all shared dependencies and implements http.Handler.

type Server struct {
    db     *sql.DB
    logger *slog.Logger
    router *http.ServeMux
}

func NewServer(db *sql.DB, logger *slog.Logger) *Server {
    s := &Server{
        db:     db,
        logger: logger,
        router: http.NewServeMux(),
    }
    s.routes()
    return s
}

func (s *Server) routes() {
    s.router.HandleFunc("GET /api/users/{id}", s.handleGetUser)
    s.router.HandleFunc("POST /api/users", s.handleCreateUser)
    s.router.HandleFunc("GET /healthz", s.handleHealth)
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    s.router.ServeHTTP(w, r)
}

Middleware Wrapping

Apply middleware at the http.Server level or per-route:

// Wrap entire server
httpServer := &http.Server{
    Addr:    ":8080",
    Handler: requestLogger(s),
}

// Or per-route
s.router.Handle("GET /api/admin/", adminOnly(http.HandlerFunc(s.handleAdmin)))

Middleware Signature

func requestLogger(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        slog.Info("request", "method", r.Method, "path", r.URL.Path, "dur", time.Since(start))
    })
}

Project Structure

Choose based on project size:

Start flat. Migrate when you see the signs described in the reference.

Graceful Shutdown

Every production Go server needs graceful shutdown. The pattern uses signal.NotifyContext to listen for OS signals and http.Server.Shutdown to drain connections.

ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()

// ... start server in goroutine ...

\x3C-ctx.Done()

shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
httpServer.Shutdown(shutdownCtx)

Full pattern with cleanup ordering in references/graceful-shutdown.md.

When to Load References

Load project-structure.md when:

  • Scaffolding a new Go project
  • Discussing package layout or directory organization
  • The project is growing and needs restructuring

Load graceful-shutdown.md when:

  • Setting up a production HTTP server
  • Implementing signal handling or clean shutdown
  • Discussing deployment or container readiness

Load dependency-injection.md when:

  • Designing how services, stores, and handlers connect
  • Making code testable with interfaces
  • Reviewing constructor functions or wiring logic

Anti-Patterns

Global database variables

// BAD -- untestable, hidden dependency
var db *sql.DB

func handleGetUser(w http.ResponseWriter, r *http.Request) {
    db.QueryRow(...)
}

Pass db through a Server or Service struct instead.

Framework-first thinking

Do not start with gin.Default() or echo.New(). Start with http.NewServeMux(). Only introduce a framework if you hit a real limitation of the stdlib that justifies the dependency.

God packages

A single handlers package with 50 files is not organization. Group by domain (user, order, billing), not by technical layer.

Using init() for setup

// BAD -- invisible side effects, untestable
func init() {
    db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
}

All initialization belongs in main() or a run() function so it can be tested and errors can be handled.

Reading config in business logic

// BAD -- couples handler to environment
func (s *Server) handleSendEmail(w http.ResponseWriter, r *http.Request) {
    apiKey := os.Getenv("SENDGRID_API_KEY") // don't do this
}

Inject configuration values or clients through constructors.

安全使用建议
This is a documentation-only skill (style guide + checks) and is internally consistent. Before installing, confirm whether you will allow the agent to read your project files and run local commands (like `go version`) — the skill's checks expect that access. The skill does not request credentials or install code, but if you permit the agent repository/toolchain access, review outputs and limit file access if you want to minimize data exposure.
功能分析
Type: OpenClaw Skill Name: go-architect Version: 2.3.1 The 'go-architect' skill bundle is a collection of best practices and architectural patterns for Go development, focusing on the net/http standard library (Go 1.22+), dependency injection, and graceful shutdown. The instructions in SKILL.md and the reference documents (dependency-injection.md, graceful-shutdown.md, project-structure.md) provide safe, idiomatic Go code examples and checklists for an AI agent to follow when reviewing or scaffolding projects. No indicators of malicious intent, data exfiltration, or prompt injection were found.
能力标签
requires-sensitive-credentials
能力评估
Purpose & Capability
The name/description match the included SKILL.md and reference files: guidance about net/http (Go 1.22+), DI, graceful shutdown, and project layout. There are no unrelated env vars, binaries, or install steps requested.
Instruction Scope
The runtime instructions include 'hard gates' that tell an agent or reviewer to check the Go toolchain (run `go version`) and inspect repository files (e.g., main.go, cmd/.../main.go). This is expected for an architecture review guide, but it means the skill assumes the agent has access to project source files and the developer toolchain; review any file-access permissions you grant the agent.
Install Mechanism
No install spec and no code files to execute — the skill is instruction-only, which minimizes install-time risk (nothing is downloaded or written to disk).
Credentials
The skill does not request environment variables or credentials. Examples in the docs reference common env usage patterns (e.g., DATABASE_URL) only as advice, not as required secrets for the skill itself.
Persistence & Privilege
always:false and no special persistence or cross-skill configuration is requested. The skill can be invoked autonomously by the agent (platform default) — this is normal; there is no additional privileged presence requested.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install go-architect
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /go-architect 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.3.1
go-architect v2.3.1 changelog: - Added an explicit "Hard gates" section to enforce step-by-step architecture checks for code reviews. - Now specifies pass/fail criteria for Go version requirements, composition root, shutdown pattern, and dependency injection. - Ensures that usage of Go 1.22+ ServeMux features requires go1.22+ toolchain, with review instructions. - Clarifies handling of configuration: handlers must not access env/globals directly, and all shared dependencies must be injected. - No functional/code logic changes outside of expanded review documentation and instructions.
v2.3.0
- Added Go 1.22+ `net/http` routing guidance, including method-based routes and path parameters. - Expanded best practices on project structure, dependency injection, and graceful shutdown, with quick-reference links to detailed guides. - Provided example code for routing, middleware, server struct patterns, and graceful shutdown handling. - Updated anti-patterns section with clear advice and code samples to avoid common mistakes. - Refined recommendations for when to use standard library vs. frameworks and when to use supporting reference material.
元数据
Slug go-architect
版本 2.3.1
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 2
常见问题

Go Architect 是什么?

Go application architecture with net/http 1.22+ routing, project structure patterns, graceful shutdown, and dependency injection. Use when building Go web se... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 161 次。

如何安装 Go Architect?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install go-architect」即可一键安装,无需额外配置。

Go Architect 是免费的吗?

是的,Go Architect 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Go Architect 支持哪些平台?

Go Architect 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Go Architect?

由 Kevin Anderson(@anderskev)开发并维护,当前版本 v2.3.1。

💬 留言讨论