🚀 GoDI: Generic based DI in Go

🚀 GoDI: Generic based DI in Go

Installation

DI:

  • go get -u github.com/MaximZayats/godi/
  • import "github.com/MaximZayats/godi/di"

CMD:

  • go get -u github.com/MaximZayats/godi/cmd/godi
  • go run github.com/MaximZayats/godi/cmd/godi init ./storage/decorators
  • go run github.com/MaximZayats/godi/cmd/godi --help

Example

  • Simple: Getting from container

    package main
    
    import (
        "fmt"
        "github.com/MaximZayats/godi/di"
    )
    
    func main() {
        di.AddSingletonByFactory[float32](func(c *di.Container) float32 {
            return 11.22
        })
    
        di.AddInstance[int](123)
    
        di.AddByFactory[string](func(c *di.Container) string {
            return "aabbcc"
        })
    
        fmt.Println(di.Get[int]())     // 123
        fmt.Println(di.Get[string]())  // "aabbcc"
        fmt.Println(di.Get[float32]()) // 11.22
        fmt.Println(di.Get[float32]()) // 11.22
    }
  • Injection: Pass arguments to function (Simple code generation is required)

    Full code: godi-fiber-example

    Snippet:

    type H = func(*fiber.Ctx) error
    
    // `stringFromDI` will be injected into the handler
    func handler(c *fiber.Ctx, stringFromDI string) error {
        return c.SendString("Hello from di: " + stringFromDI)
    }
    
    func main() {
        di.AddInstance[string]("I'm string from DI!!!", c)
        ...
        app.Get("/", injection.Inject[H](handler))
    }

Other examples

Usage

  1. Getting from container:

    • See examples above
  2. Injection (decorating):

    • Generate package for storing decorators:
      • go run github.com/MaximZayats/godi/cmd/godi init ./storage/decorators
      • Configure godi.injection:
        • import (
              ".../storage/decorators"
              "github.com/MaximZayats/godi/injection"
          )
          
          injection.Configure(decorators.Config)
      • Use injection:
        • // `a` and `b` will be auto injected in the function
          func Handler(c context.Context, a int, b string) int {
              fmt.Println(c, a, b)
              return a
          }
          
          injection.Configure(decorators.Config)
          
          // H is the type alias for the function after injection
          type H = func(context.Context) int
          decoratedHandler := injection.Inject[H](Handler)
          
          // IMPORTANT! You need to verify injection
          injection.MustVerifyInjections()
          
          decoratedHandler(context.TODO())
          See full example

Benchmarks

Code

goos: windows
goarch: amd64
pkg: github.com/MaximZayats/godi/benchmark
cpu: AMD Ryzen 5 1600 Six-Core Processor
BenchmarkGetFromFactorySingleton
BenchmarkGetFromFactorySingleton-12     500488393                2.443 ns/op
BenchmarkGetInstance
BenchmarkGetInstance-12                 495795447                2.403 ns/op
BenchmarkGetFromFactory
BenchmarkGetFromFactory-12              361722957                3.273 ns/op
PASS
Similar Resources

A Golang tool to whitelist ASN's based on organization name

A Golang tool to whitelist ASN's based on organization name. This works by providing a list of ASN org names. This tool uses goPacket to monitor incoming traffic, capturing the IP's and checking the IP to see if it is a part of a whitelisted ASN. If it is not, it blocks that connection and future connections using iptables.

Jul 23, 2022

ptypes is a pointer-based box typing system for golang.

ptypes bypass go's type system through unsafe pointers the paradigm is to created a "boxed" type with .From and then use whatever types we want by ass

Aug 26, 2021

Fast, scalable pseudo random number generator based on xxh3

Fast, scalable pseudo random number generator based on xxh3

XXH3-Based Pseudorandom Number Generator This package contains an experimental implementation of a noise based pseudorandom number generator that scal

Nov 24, 2022

Script Based Alerting Manager

Script Based Alerting Manager

A Project in active development. Features may have breaking changes at any time before v1.0.0 version Telegram Group Balerter is a scripts based alert

Dec 27, 2022

A concurrent rate limiter library for Golang based on Sliding-Window rate limiter algorithm.

ratelimiter A generic concurrent rate limiter library for Golang based on Sliding-window rate limitng algorithm. The implementation of rate-limiter al

Jan 6, 2023

Daypaper sets your GNOME wallpaper based on the time of day from a random and relevant Unsplash image.

Daypaper Daypaper sets your GNOME wallpaper based on the time of day from a random and relevant Unsplash image. Installation You will need an Access T

May 23, 2022

CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON.

Cuetils CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON. Using As a command line binary The cu

Dec 24, 2022

Configuration based URL shortner useful for on page 301 redirects

GO_URL_SHORT Configuration based URL shortner useful for on page 301 redirects Configuration for shortened url can be loaded from a JSON file in forma

Oct 16, 2021

The main goal of this code is to create a basic dnstap printing tool based on the golang-dnstap library.

dnstap-parse The main goal of this code is to create a basic dnstap printing tool based on the golang-dnstap library. The output is supposed to mimic

Nov 14, 2021
Generic-based collection tools

go-collection go collection is a tool implemented using generic, it can help you process slice/map data quickly and easily convert between them. Note:

Dec 29, 2022
A better Generic Pool (sync.Pool)
A better Generic Pool (sync.Pool)

This package is a thin wrapper over the Pool provided by the sync package. The Pool is an essential package to obtain maximum performance by reducing the number of memory allocations.

Dec 1, 2022
Package ethtool allows control of the Linux ethtool generic netlink interface.

ethtool Package ethtool allows control of the Linux ethtool generic netlink interface.

Dec 14, 2022
Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Dec 28, 2022
conditiond is a generic constraint and policy evaluator.

conditiond conditiond is a generic constraint and policy evaluator. This tool lets you define constraints in data and evaluate them at run time. It's

Dec 5, 2022
Some utility functions for generic types in Go.

GOUF - Utility Functions for generic types Go team released Go 1.18 beta recently with support for Generics(a.k.a type parameters). This package provi

Apr 13, 2022
Generic Free List implementation to reuse memory and avoid allocations

gofl GOFL provides a Generic Free List implementation for Go. Installation This

Oct 17, 2022
Slice - provides generic Map, Reduce and Filter functions for Go.

slice slice is a simple Go package to provide generic versions of Map, Reduce and Filter on slices. I mainly wrote it as an exercise to get more famil

Jan 1, 2023
go generate based graphql server library
go generate based graphql server library

gqlgen What is gqlgen? gqlgen is a Go library for building GraphQL servers without any fuss. gqlgen is based on a Schema first approach — You get to D

Dec 29, 2022
A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. 🔃

go-hashlru A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. ?? Uses map[interface{}]interface{} to allow

Dec 5, 2022