Xpersona
G

golang-samber-do

CLAWHUB · Unverified

Dependency injection in Golang using samber/do — service containers, lifecycle management, scopes, health checks, graceful shutdown, and module organization. Apply when using or adopting samber/do, when the codebase imports github.com/samber/do or github.com/samber/do/v2, or when refactoring manual constructor injection into a DI container.

62
Rank
84
Safety
1.2k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-do
  1. Install using `clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-do` in an isolated environment before connecting it to live workloads.
  2. No published capability contract is available yet, so validate auth and request/response behavior manually.
  3. Review the upstream CLAWHUB listing at https://clawhub.ai/samber/golang-samber-do before using production credentials.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-samber-do/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

129,566 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: golang-samber-do
description: "Dependency injection in Golang using samber/do — service containers, lifecycle management, scopes, health checks, graceful shutdown, and module organization. Apply when using or adopting samber/do, when the codebase imports github.com/samber/do or github.com/samber/do/v2, or when refactoring manual constructor injection into a DI container."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.3.0"
  openclaw:
    emoji: "💉"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
    skill-library-version: "2.0.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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:**

- [pkg.go.dev/github.com/samber/do/v2](https://pkg.go.dev/github.com/samber/do/v2)
- [do.samber.dev](https://do.samber.dev)
- [github.com/samber/do/v2](https://github.com/samber/do)

This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See `samber/cc-skills-golang@golang-gopls` skill (`gopls`). Context7 remains a fallback for docs not indexed on pkg.go.dev.

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

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

## Core Concepts

### The Injector (Container)

```go
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:

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

## Basic Usage

### 1. Define and Register Services

Follow "Accept Interfaces, Return Structs":

```go
// 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 servic

_meta.json

{
  "ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
  "slug": "golang-samber-do",
  "version": "1.3.0",
  "publishedAt": 1787409974746
}

references/advanced.md

# Advanced Usage

## Scopes (Module Tree)

Scopes SHOULD be used to organize services by module:

```go
root := do.New()

// Register shared services in root
do.Provide(root, func(i do.Injector) (Database, error) {
    return &Database{}, nil
})

// Create child scope
apiScope := root.Scope("api")

// Services in apiScope can access root services
do.Provide(apiScope, func(i do.Injector) (UserService, error) {
    db := do.MustInvoke[Database](i) // from root
    return &userService{db: db}, nil
})

// Child scopes are isolated from each other
userScope := root.Scope("user")
```

Organize services by lifecycle and visibility:

```go
root := do.New()

// Global/stateless services in root
do.Provide(root, NewConfig)
do.Provide(root, NewLogger)

// Request-scoped services
requestScope := root.Scope("request")
do.Provide(requestScope, NewRequestContext)
```

## Explicit Service Aliasing

For rare cases when you need to adapt to legacy code:

```go
do.Provide(injector, func(i do.Injector) (*PostgreSQLDatabase, error) {
    return &PostgreSQLDatabase{}, nil
})

do.MustAs[*PostgreSQLDatabase, Database](injector)

// Now both work:
db1 := do.MustInvoke[*PostgreSQLDatabase](injector)
db2 := do.MustInvoke[Database](injector)
```

Prefer implicit aliasing with `InvokeAs()` in most cases.

## Struct Injection

Inject services directly into struct fields using tags:

```go
type App struct {
    Database *Database `do:""`
    Logger   *Logger   `do:"app-logger"`
    Config   *Config   `do:""`
}

app := do.MustInvokeStruct[App](injector)
```

## Lifecycle Management

### Health Checks

Implement the `Healthchecker` interface:

```go
func (d *Database) HealthCheck() error {
    return d.conn.Ping()
}

// With context support:
func (d *Database) HealthCheck(ctx context.Context) error {
    return d.conn.PingContext(ctx)
}

// Check health
if err := do.HealthCheck[Database](injector); err != nil {
    log.Printf("Database unhealthy: %v", err)
}
```

### Graceful Shutdown

Implement the `Shutdowner` interface (4 variants):

```go
// Simple
func (d *Database) Shutdown() { d.conn.Close() }

// With context
func (d *Database) Shutdown(ctx context.Context) { d.conn.Close() }

// With error
func (d *Database) Shutdown() error { return d.conn.Close() }

// With context + error (most flexible)
func (d *Database) Shutdown(ctx context.Context) error { return d.conn.Close() }
```

Shutdown with timeout:

```go
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

report := injector.ShutdownWithContext(ctx)
```

## Debugging

### List Services

```go
services := injector.ListProvidedServices()
for _, svc := range services {
    fmt.Printf("%s: %s\n", svc.ScopeName, svc.Service)
}
```

### Explain Injector

```go
explanation := do.ExplainInjector(injector)
fmt.Println(explanation.String())
```

## Migration from Manual DI

Before (manual):

```go
func main() {
    config := &Config{Port: 8080}
    db := NewDatabase(config)
    userRepo := NewU

references/testing.md

# Testing with samber/do

## Container Cloning

Clone containers for isolated tests:

```go
func TestUserService(t *testing.T) {
    // Create test container by cloning main container
    testInjector := mainInjector.Clone()

    // Override with mocks
    mockDB := &MockDatabase{}
    do.OverrideValue(testInjector, mockDB)

    // Test with mocked dependencies
    service := do.MustInvoke[UserService](testInjector)
    // ... test code
}
```

## Reusable Test Helpers

```go
func SetupTestContainer(t *testing.T) do.Injector {
    injector := do.New()

    do.Provide(injector, func(i do.Injector) (Database, error) {
        return &MockDatabase{}, nil
    })

    return injector
}
```

## Quick Reference

### Testing & Overrides

| Function                         | Purpose                         |
| -------------------------------- | ------------------------------- |
| `injector.Clone()`               | Clone container for testing     |
| `injector.CloneWithOpts()`       | Clone with custom options       |
| `do.Override[T]()`               | Replace service (use in tests)  |
| `do.OverrideNamed[T]()`          | Replace named service           |
| `do.OverrideValue[T]()`          | Replace value service           |
| `do.OverrideNamedValue[T]()`     | Replace named value             |
| `do.OverrideTransient[T]()`      | Replace transient factory       |
| `do.OverrideNamedTransient[T]()` | Replace named transient factory |

skill-card.md

## Description:

Dependency injection in Golang using samber/do: service containers, lifecycle management, scopes, health checks, graceful shutdown, and module organization.

This skill is ready for commercial/non-commercial use.

## Publisher:

[samber](https://clawhub.ai/user/samber)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and engineers use this skill when adopting or maintaining samber/do in Go projects, especially when setting up dependency injection containers, service lifecycles, package registration, testing overrides, health checks, and graceful shutdown.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: The skill may lead an agent to edit Go files, run Go tooling, or add github.com/samber/do/v2 to a module.

Mitigation: Review Go source changes, go.mod, and go.sum, and run the project's normal Go tests before accepting dependency-injection changes.

Risk: Using the wrong samber/do import path or lifecycle pattern can create incorrect dependency-injection behavior.

Mitigation: Verify generated code uses github.com/samber/do/v2, keeps container access at the composition root, and follows the skill's service lifecycle guidance.

## Reference(s):

- [ClawHub skill page](https://clawhub.ai/samber/skills/golang-samber-do)
- [Skill homepage](https://github.com/samber/cc-skills-golang)
- [pkg.go.dev samber/do v2](https://pkg.go.dev/github.com/samber/do/v2)
- [samber/do documentation](https://do.samber.dev)
- [samber/do source repository](https://github.com/samber/do)
- [Advanced Usage](references/advanced.md)
- [Testing with samber/do](references/testing.md)

## Skill Output:

**Output Type(s):** [Text, Markdown, Code, Shell commands, Configuration, Guidance]

**Output Format:** [Markdown guidance with Go code examples and shell command snippets]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [May propose Go file edits and Go module dependency changes when requested by the user.]

## Skill Version(s):

1.3.0 (source: server release evidence and artifact frontmatter)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to golang-samber-do and adjacent AI workflows.