Skip to content

gburgyan/go-ctxdep

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

118 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build status Go Report Card PkgGoDev

go-ctxdep

Context-based dependency management for Go - simple, type-safe, and test-friendly.

Go already has a nice way to keep track of things with context.Context. This library adds helpers to simplify getting things out of that context, with support for lazy initialization, caching, and clean testing patterns.

Installation

go get github.com/gburgyan/go-ctxdep

Quick Example

type UserService struct {
    // ...
}

func main() {
    ctx := ctxdep.NewDependencyContext(context.Background(), &UserService{})
    handleRequest(ctx)
}

func handleRequest(ctx context.Context) {
    svc := ctxdep.Get[*UserService](ctx)
    // use svc...
}

Design Goals

  • Simple interface built on Go's context.Context
  • Type-safe access to dependencies
  • Thread-safe with no deadlock risks
  • Fail-fast - errors surface immediately, not in production
  • Fast dependency resolution
  • Explicit over magic - no hidden configuration
  • Easy testing - the main motivation for this library

Documentation

Full documentation is available in the docs/ directory:

Getting Started

Key Features

Additional Features

Advanced

Why This Library?

Testing. Testing is what started the idea for this.

Without a way to manage dependencies through context, overriding them in tests is awkward:

// Hard to test - how do you mock GetUserData?
func isPermitted(request *Request) bool {
    userData := user.GetUserData(request.userId)
    return userData.IsAdmin
}

With go-ctxdep:

func isPermitted(ctx context.Context) bool {
    user := ctxdep.Get[*UserData](ctx)
    return user.IsAdmin
}

func Test_isPermitted(t *testing.T) {
    ctx := ctxdep.NewDependencyContext(context.Background(),
        &UserData{IsAdmin: true},
    )
    assert.True(t, isPermitted(ctx))
}

Each test gets its own context. No global state. No race conditions. No mocking frameworks.

See the Testing Guide for comprehensive patterns.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A simple way to manage contextual objects for your system.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages