Community코딩 & 개발github.com

samber/golang-samber-do

Golang에서 samber/do를 사용한 의존성 주입 — 서비스 컨테이너, 생명주기 관리, 범위, 헬스 체크, 정상 종료, 모듈 구성. samber/do를 사용하거나 도입할 때, 코드베이스가 github.com/samber/do 또는 github.com/samber/do/v2를 임포트할 때, 또는 수동 생성자 주입을 DI 컨테이너로 리팩토링할 때 적용하세요.

golang-samber-do란 무엇인가요?

이 스킬은 Golang 애플리케이션에서 `samber/do` 라이브러리를 사용한 의존성 주입(DI)을 위한 완전한 가이드를 제공합니다. 서비스 컨테이너 등록, 생명주기 관리(지연 초기화, 조기 초기화), 요청 범위나 전송 범위와 같은 다양한 DI 범위, 헬스 체크 및 정상 종료 메커니즘을 다룹니다. `samber/do`는 Claude Code, Cursor와 같은 AI 에이전트 도구를 포함한 모든 Go 개발 환경과 호환되는 간단하고 강력한 DI 컨테이너입니다. 이 스킬은 수동 생성자 주입을 DI 컨테이너로 리팩토링하는 방법, 서비스를 모듈로 구성하는 방법(HTTP 핸들러 설정, 데이터베이스 연결 풀 관리, 로거 초기화 등), 그리고 컨테이너 해제 시 리소스를 정리하는 방법을 명확히 설명합니다. 가비지 컬렉션 누수 방지나 명시적인 서비스 제거와 같은 일반적인 문제를 피하는 방법도 다룹니다. 이 스킬을 사용하면 AI 에이전트가 명확하고 유지보수 가능하며 테스트 가능한 Go 코드를 `samber/do` DI 패턴으로 생성할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/samber/cc-skills-golang/tree/main/skills/golang-samber-do

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

golang-samber-do은(는) 무엇을 하나요?

Golang에서 samber/do를 사용한 의존성 주입 — 서비스 컨테이너, 생명주기 관리, 범위, 헬스 체크, 정상 종료, 모듈 구성. samber/do를 사용하거나 도입할 때, 코드베이스가 github.com/samber/do 또는 github.com/samber/do/v2를 임포트할 때, 또는 수동 생성자 주입을 DI 컨테이너로 리팩토링할 때 적용하세요.

개요

  • 라이브러리: samber/do (v1.x)
  • 목적: Go 애플리케이션을 위한 범용 의존성 주입 컨테이너 제공
  • 핵심 개념: 서비스 제공자, 범위(Scopes), 생명주기, 헬스 체크, 정상 종료
  • 호환성: 표준 Go, 대부분의 웹 프레임워크, Claude Code, Cursor, Codex와 같은 AI 코딩 에이전트

설치

go get github.com/samber/do@v1

기본 사용법

1. 서비스 제공자 등록

package main

import (
    "github.com/samber/do"
)

type MyService struct {
    Name string
}

func main() {
    // 컨테이너 생성
    container := do.New()
    defer container.Shutdown()

    // 서비스 제공자 등록
    do.Provide(container, func(c *do.Container) (*MyService, error) {
        return &MyService{Name: "hello"}, nil
    })

    // 컨테이너에서 서비스 가져오기
    svc, err := do.Invoke[*MyService](container)
    if err != nil {
        panic(err)
    }
    println(svc.Name) // "hello" 출력
}

2. 생명주기 관리

samber/do는 서비스 생명주기 관리 내장 지원을 제공합니다:

  • Lazy(기본): 첫 번째 호출 시 초기화
  • Eager: 컨테이너 빌드 시 즉시 초기화 (do.ProvideValue 사용 시)
  • Transient(일시적): 호출할 때마다 새 인스턴스 생성
// 지연 초기화 (기본 동작)
do.Provide(container, func(c *do.Container) (*MyService, error) {
    return &MyService{}, nil
})

// 조기 초기화 (값 등록)
do.ProvideValue(container, &MyService{Name: "eager"})

// 일시적 서비스 (호출할 때마다 새 인스턴스)
do.ProvideTransient(container, func(c *do.Container) (*MyService, error) {
    return &MyService{}, nil
})

3. 의존성 주입

type Database struct {
    DSN string
}

type UserRepository struct {
    db *Database
}

func main() {
    container := do.New()
    defer container.Shutdown()

    // 데이터베이스 서비스 등록
    do.Provide(container, func(c *do.Container) (*Database, error) {
        return &Database{DSN: "postgres://localhost:5432/mydb"}, nil
    })

    // 데이터베이스에 의존하는 UserRepository 등록
    do.Provide(container, func(c *do.Container) (*UserRepository, error) {
        db, err := do.Invoke[*Database](c)
        if err != nil {
            return nil, err
        }
        return &UserRepository{db: db}, nil
    })

    // UserRepository 가져오기 (데이터베이스가 자동으로 주입됨)
    repo, _ := do.Invoke[*UserRepository](container)
    _ = repo
}

고급 사용법

서비스 범위 (Scopes)

do.Scope를 사용하여 요청 범위의 서비스를 생성합니다:

func main() {
    root := do.New()
    defer root.Shutdown()

    // 루트 범위에 데이터베이스 등록
    do.Provide(root, func(c *do.Container) (*Database, error) {
        return &Database{DSN: "postgres://..."}, nil
    })

    // 각 요청에 대한 범위 생성
    requestScope := root.Scope("request-1")
    defer requestScope.Shutdown()

    // 요청 범위 서비스는 루트 서비스를 재정의할 수 있습니다
    do.Provide(requestScope, func(c *do.Container) (*RequestContext, error) {
        return &RequestContext{UserID: "123"}, nil
    })
}

헬스 체크

samber/do는 서비스에 건강 상태 확인을 연결할 수 있습니다:

do.Provide(container, func(c *do.Container) (*Database, error) {
    return &Database{}, nil
})

// 데이터베이스에 대한 헬스 체크 등록
do.HealthCheck[Database](container, "database.health", func(db *Database) (bool, error) {
    err := db.Ping()
    if err != nil {
        return false, err
    }
    return true, nil
})

// 모든 헬스 체크 실행
healthy, err := do.HealthCheckAll(container)
if err != nil {
    log.Printf("헬스 체크 실패: %v", err)
}

정상 종료 (Graceful Shutdown)

컨테이너가 종료될 때 정리 로직을 정의합니다:

do.Provide(container, func(c *do.Container) (*Database, error) {
    db := &Database{}
    // 연결 열기
    db.Connect()
    return db, nil
})

// shutdown 함수 등록
do.AddShutdown(container, func() error {
    println("데이터베이스 연결 종료 중...")
    return nil
})

// 컨테이너 종료 (등록된 모든 shutdown 함수가 역순으로 실행됨)
container.Shutdown()

모범 사례

모듈별 서비스 구성

관련 서비스를 모듈 함수로 그룹화하세요:

// database/module.go
package database

import "github.com/samber/do"

func Module(container *do.Container) {
    do.Provide(container, NewConnection)
    do.Provide(container, NewRepository)
    do.HealthCheck[Connection](container, "db.ping", func(c *Connection) (bool, error) {
        return c.Ping(), nil
    })
}

// main.go
package main

import (
    "myapp/database"
    "github.com/samber/do"
)

func main() {
    container := do.New()
    defer container.Shutdown()

    database.Module(container)

    // 모든 애플리케이션 서비스 사용 가능
}

일반적인 함정 피하기

  1. 순환 의존성: 서비스 제공자에서 직접적인 순환 참조를 피하세요. 대신 인터페이스를 사용하거나 지연 초기화 패턴을 사용하세요.
  2. GC 누수: 모든 서비스가 더 이상 필요하지 않으면 제거되었는지 확인하세요. 컨테이너를 주기적으로 정리하거나 서비스 수명이 짧은 범위를 사용하세요.
  3. 명시적 제거: container.Remove(name) 또는 container.RemoveAll()을 사용하여 서비스를 명시적으로 제거할 수 있지만, 일반적으로는 범위를 사용하는 것이 더 좋습니다.

문제 해결

  • ErrMissingDependency: 컨테이너가 아직 제공되지 않은 서비스를 요청할 때 발생합니다. 종속성이 올바른 순서로 등록되었는지 확인하세요.
  • ErrServiceNotFound: 지정된 이름의 서비스가 없습니다. 서비스 이름이 일치하는지 확인하세요.
  • 성능: 지연 초기화는 시작 시간을 개선하지만 첫 번째 요청을 느리게 만들 수 있습니다. 중요 서비스에는 조기 초기화를 사용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

samber/golang-benchmark

Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hot paths with pprof, interpreting CPU/memory/trace profiles, analyzing results with benchstat, setting up CI benchmark regression detection, or investigating production performance with Prometheus runtime metrics. Also use when the developer needs deep analysis on a specific performance indicator - this skill provides the measurement methodology, while `samber/cc-skills-golang@golang-performance` provides the optimization patterns.

samber/golang-cli

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also triggers when code uses cobra, viper, or urfave/cli. For cobra-specific APIs → See `samber/cc-skills-golang@golang-spf13-cobra` skill; for viper configuration layering → See `samber/cc-skills-golang@golang-spf13-viper` skill.

samber/golang-code-style

Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).

samber/golang-concurrency

Golang concurrency patterns. Use when writing or reviewing concurrent Go code involving goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools, or fan-out/fan-in pipelines. Also triggers when you detect goroutine leaks, race conditions, channel ownership issues, or need to choose between channels and mutexes.

samber/golang-context

Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter.

samber/golang-continuous-integration

CI/CD pipeline configuration using GitHub Actions for Golang projects — testing, linting, SAST, security scanning, code coverage, Dependabot, Renovate, GoReleaser, code review automation, and release pipelines. Use when setting up or improving Go project CI, configuring GitHub Actions workflows, adding linters or security scanners, automating dependency updates, or adding quality gates.

samber/golang-database

Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interacts with PostgreSQL, MariaDB, MySQL, or SQLite; for database testing; or for questions about database/sql, sqlx, or pgx. Does NOT generate database schemas or migration SQL.

samber/golang-data-structures

Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals.

samber/golang-dependency-injection

Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, → See `samber/cc-skills-golang@golang-google-wire`, `samber/cc-skills-golang@golang-uber-dig`, `samber/cc-skills-golang@golang-uber-fx`, or `samber/cc-skills-golang@golang-samber-do` skills.

samber/golang-dependency-management

Dependency management strategies for Golang projects — go.mod management, installing/upgrading packages, Minimal Version Selection, vulnerability scanning, outdated dependency tracking, binary size analysis, Dependabot/Renovate setup, conflict resolution, and go.work workspaces. Use when adding, removing, or upgrading Go dependencies, auditing vulnerabilities, resolving version conflicts, or setting up automated dependency updates.

samber/golang-design-patterns

Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, streaming, and more. Apply when explicitly choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem.

samber/golang-documentation

Comprehensive documentation guide for Golang projects, covering godoc comments, README, CONTRIBUTING, CHANGELOG, Go Playground, Example tests, API docs, and llms.txt. Use when writing or reviewing doc comments, documentation, adding code examples, setting up doc sites, or discussing documentation best practices. Triggers for both libraries and applications/CLIs.

samber/golang-error-handling

Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops` skill; for slog handler ecosystem → See `samber/cc-skills-golang@golang-samber-slog` skill.

samber/golang-google-wire

Compile-time dependency injection in Golang using google/wire — wire.NewSet, wire.Build, wire.Bind (interface→concrete), wire.Struct, wire.Value, wire.InterfaceValue, wire.FieldsOf, cleanup functions, //go:build wireinject injector files, and generated wire_gen.go. Apply when using or adopting google/wire, when the codebase imports `github.com/google/wire`, or when wiring an application graph at compile time via `wire.Build`. For runtime DI with reflection, see `samber/cc-skills-golang@golang-uber-dig` skill.

samber/golang-gopls

Golang semantic code intelligence via `gopls`, the official Go language server — go-to-definition, find references, call/implementation hierarchy, workspace symbol search, package API discovery, diagnostics, safe rename, refactors (extract/inline/fill/rewrite code actions), formatting, and generated tests. Reaches an agent via gopls's own MCP server (`go_*` tools), Claude Code's native `LSP` tool, or the `gopls` CLI. Use when navigating or refactoring Go code — jumping to a definition, finding call sites before a rename, understanding a file's or package's dependencies, running diagnostics after an edit, or extracting/inlining/renaming. Not for the published ecosystem — packages not in your `go.mod`, versions, licenses, importers — → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`). Not for a whole-tree vulnerability audit → See `samber/cc-skills-golang@golang-security` skill (`govulncheck`).

samber/golang-graphql

Implements GraphQL APIs in Golang using gqlgen or graphql-go. Apply when building GraphQL servers, designing schemas, writing resolvers, handling subscriptions, or integrating GraphQL with existing Go HTTP services. Also apply when the codebase imports `github.com/99designs/gqlgen` or `github.com/graph-gophers/graphql-go`.

samber/golang-grpc

Provides gRPC usage guidelines, protobuf organization, and production-ready patterns for Golang microservices. Use when implementing, reviewing, or debugging gRPC servers/clients, writing proto files, setting up interceptors, handling gRPC errors with status codes, configuring TLS/mTLS, testing with bufconn, or working with streaming RPCs.

samber/golang-how-to

Golang skills orchestrator — always active on any Golang coding, review, debug, or setup task. Reads the task context and loads the most relevant skills from samber/cc-skills-golang, often multiple at once: writing a gRPC service loads golang-grpc + golang-testing + golang-error-handling; debugging a panic loads golang-troubleshooting + golang-safety; auditing security loads golang-security + golang-lint + golang-safety. Also: disambiguates competing clusters when two skills seem to overlap (performance vs benchmark vs troubleshooting, samber/lo vs mo vs ro, DI cluster, safety vs security), and configures the project's agent-config file (CLAUDE.md, AGENTS.md, GEMINI.md, Cursor rules, or Copilot instructions) to force-trigger skills in a project (/golang-how-to configure).

samber/golang-lint

Linting best practices and golangci-lint configuration for Golang projects — running linters, configuring .golangci.yml, suppressing warnings with nolint directives, interpreting lint output, and selecting linters. Use when configuring golangci-lint, asking about lint warnings or nolint suppressions, setting up code quality tooling, or choosing linters. Also use when the user mentions golangci-lint, go vet, staticcheck, or revive.

samber/golang-modernize

Modernize Golang code to use recent language features, standard library improvements, and idiomatic patterns. Trigger proactively when writing or reviewing Go code and old-style patterns are detected, or when encountering a deprecation warning. Also use when the user explicitly asks for modernization, a Go version upgrade, or a CI/tooling refresh.

관련 스킬