← 返回 Skills 市场
samber

Golang Samber Do

作者 Samuel Berthe · GitHub ↗ · v1.1.3 · MIT-0
cross-platform ✓ 安全检测通过
180
总下载
0
收藏
1
当前安装
3
版本数
在 OpenClaw 中安装
/install golang-samber-do
功能描述
Implements dependency injection in Golang using samber/do. Apply this skill when working with dependency injection, setting up service containers, managing s...
使用说明 (SKILL.md)

Persona: You are a Go architect setting up dependency injection. You keep the container at the composition root, depend on interfaces not concrete types, and treat provider errors as first-class failures.

Using samber/do for Dependency Injection in Go

Type-safe dependency injection toolkit for Go based on Go 1.18+ generics.

Official Resources:

This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.

DO NOT USE v1 OF THIS LIBRARY. INSTALL v2 INSTEAD:

go get -u github.com/samber/do/v2

Core Concepts

The Injector (Container)

import "github.com/samber/do/v2"

injector := do.New()

Service Types

  • Lazy (default): Created when first requested
  • Eager: Created immediately when the container starts
  • Transient: New instance created on every request
  • Value: Pre-created value, no instantiation

Provider Functions

Services MUST be registered via provider functions:

type Provider[T any] func(i Injector) (T, error)

Basic Usage

1. Define and Register Services

Follow "Accept Interfaces, Return Structs":

// Register a service (lazy by default)
do.Provide(injector, func(i do.Injector) (Database, error) {
    return &PostgreSQLDatabase{connString: "postgres://..."}, nil
})

// Register a pre-created value
do.ProvideValue(injector, &Config{Port: 8080})

// Register a transient service (new instance each time)
do.ProvideTransient(injector, func(i do.Injector) (*Logger, error) {
    return &Logger{}, nil
})

// Register an eager service (created immediately)
do.Provide(injector, do.Eager(&Config{Port: 8080}))

2. Invoke Services

The container MUST only be accessed at the composition root:

// Invoke with error handling
db, err := do.Invoke[Database](injector)

// MustInvoke panics on error (use when confident service exists)
db := do.MustInvoke[Database](injector)

3. Service Dependencies

func NewUserService(i do.Injector) (UserService, error) {
    db := do.MustInvoke[Database](i)
    cache := do.MustInvoke[Cache](i)
    return &userService{db: db, cache: cache}, nil
}

do.Provide(injector, NewUserService)

4. Implicit Aliasing (Preferred)

Register a concrete type and invoke as an interface without explicit aliasing:

// Register concrete type
do.Provide(injector, func(i do.Injector) (*PostgreSQLDatabase, error) {
    return &PostgreSQLDatabase{}, nil
})

// Invoke directly as interface (implicit aliasing)
db := do.MustInvokeAs[Database](injector)

5. Named Services

Register multiple services of the same type:

do.ProvideNamed(injector, "primary-db", func(i do.Injector) (*Database, error) {
    return &Database{URL: "postgres://primary..."}, nil
})

mainDB := do.MustInvokeNamed[*Database](injector, "primary-db")

Package Organization

Use do.Package() to organize service registration by module:

// infrastructure/package.go
var Package = do.Package(
    do.Lazy(func(i do.Injector) (*postgres.DB, error) {
        cfg := do.MustInvoke[*Config](i)
        return postgres.Connect(cfg.DatabaseURL)
    }),
    do.Lazy(func(i do.Injector) (*redis.Client, error) {
        cfg := do.MustInvoke[*Config](i)
        return redis.NewClient(cfg.RedisURL), nil
    }),
)

// main.go
injector := do.New(infrastructure.Package, service.Package)

Full Application Setup

func main() {
    injector := do.New(
        infrastructure.Package,
        repository.Package,
        service.Package,
        transport.Package,
    )

    server := do.MustInvoke[*http.Server](injector)
    go server.ListenAndServe()

    _ = injector.ShutdownOnSignalsWithContext(context.Background(), os.Interrupt)
}

Best Practices

  1. Depend on interfaces, not concrete types — lets you swap implementations in tests without touching production code
  2. Each service should have one job — services with multiple responsibilities are harder to test and harder to replace
  3. Keep dependency trees shallow — chains beyond 3-4 levels make initialization order fragile and errors harder to trace
  4. Handle errors in provider functions — a silently failing provider creates a broken service that crashes later in unexpected places
  5. Use scopes to organize services by lifecycle — request-scoped services prevent leaks, global services prevent redundant initialization

For scopes, lifecycle management, struct injection, and debugging, see Advanced Usage.

For testing patterns (cloning, overrides, mocks), see Testing.

Quick Reference

Registration

Function Purpose
do.Provide[T]() Register lazy service (default)
do.ProvideNamed[T]() Register named lazy service
do.ProvideValue[T]() Register pre-created value
do.ProvideNamedValue[T]() Register named value
do.ProvideTransient[T]() Register new instance each time
do.ProvideNamedTransient[T]() Register named transient service
do.Package() Group service registrations

Invocation

Function Purpose
do.Invoke[T]() Get service (with error)
do.InvokeNamed[T]() Get named service
do.InvokeAs[T]() Get first service matching interface
do.InvokeStruct[T]() Inject into struct fields using tags
do.MustInvoke[T]() Get service (panic on error)
do.MustInvokeNamed[T]() Get named service (panic on error)
do.MustInvokeAs[T]() Get service by interface (panic on error)
do.MustInvokeStruct[T]() Inject into struct (panic on error)

Cross-References

  • → See samber/cc-skills-golang@golang-dependency-injection skill for DI concepts, comparison, and when to adopt a DI library
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface design patterns
  • → See samber/cc-skills-golang@golang-testing skill for general testing patterns
安全使用建议
This skill is a documentation-style, instruction-only helper for using samber/do v2 and appears internally consistent. Things to consider before enabling: (1) The SKILL.md suggests running 'go get -u', which will modify module files (go.mod/go.sum) in your project—run it in a safe branch or sandbox if you're cautious. (2) The allowed tools include web fetch and git commands; these are reasonable for a coding assistant but will allow the agent to access docs/repos—ensure you trust the agent session and that no sensitive data is exposed. (3) The skill enforces v2 usage (good); verify your project is ready for the v2 API before applying changes. Overall the skill is coherent with its stated purpose and does not request unrelated credentials or system access.
功能分析
Type: OpenClaw Skill Name: golang-samber-do Version: 1.1.3 The skill bundle provides legitimate and well-structured instructions for implementing dependency injection in Go using the 'samber/do/v2' library. It includes comprehensive documentation on service lifecycles, package organization, and testing patterns (SKILL.md, advanced.md, testing.md). No evidence of malicious intent, data exfiltration, or harmful prompt injection was found.
能力评估
Purpose & Capability
Name/description say 'dependency injection with samber/do' and the SKILL.md only describes how to use that library. The only declared runtime requirement is the 'go' binary which is appropriate for a Go-focused coding/teaching skill.
Instruction Scope
The instructions are limited to installing and using github.com/samber/do/v2, registering providers, scopes, testing patterns, health checks, and graceful shutdown. They do not instruct reading unrelated files, harvesting environment variables, or sending project data to external endpoints beyond normal library documentation links and a go get command.
Install Mechanism
This is an instruction-only skill (no install spec). The SKILL.md recommends running 'go get -u github.com/samber/do/v2' which is the expected way to add the library; nothing is downloaded from obscure URLs or written by the skill itself.
Credentials
The skill requests no environment variables, no credentials, and no config paths. That is proportionate for a documentation/guide skill about a Go DI library.
Persistence & Privilege
always:false and no install step means the skill does not request permanent presence or elevated privileges. disable-model-invocation is false (agent may invoke autonomously) but there are no additional red flags that amplify risk.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-samber-do
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-samber-do 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.1.3
- Bumped skill version to 1.1.3. - Fixed a typo in documentation: "informations" → "information". - Updated cross-reference arrows for consistency (-> → →). - No functional or API changes. Documentation only.
v1.1.2
- Bumped skill version to 1.1.2. - Added evals/evals.json file. - Updated resource link in SKILL.md to reference github.com/samber/do/v2. - Minor metadata cleanup and description quoting in SKILL.md.
v0.1.0
Initial release of golang-samber-do skill: - Provides concise guidelines and best practices for using samber/do v2 for dependency injection in Go. - Includes code examples for service registration, invocation, aliasing, named services, and modular package organization. - Contains quick reference tables for core samber/do API functions. - Highlights best practices such as depending on interfaces, managing service lifecycles, and error handling in providers. - Cross-references related skills for deeper DI concepts, interface patterns, and Go testing approaches.
元数据
Slug golang-samber-do
版本 1.1.3
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 3
常见问题

Golang Samber Do 是什么?

Implements dependency injection in Golang using samber/do. Apply this skill when working with dependency injection, setting up service containers, managing s... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 180 次。

如何安装 Golang Samber Do?

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

Golang Samber Do 是免费的吗?

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

Golang Samber Do 支持哪些平台?

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

谁开发了 Golang Samber Do?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.1.3。

💬 留言讨论