Jacket of google/wire: advanced DI approach wrapping google/wire for cloud.

Wire-Jacket: IoC Container of google/wire for cloud-native

GoDoc Github release Build Status Coverage Status Go Report Card

Jacket of google/wire: advanced DI approach wrapping google/wire for cloud.

A jacket is an outer sheath that groups wires and protects the core from external issues.

wire-jacket wraps google/wire and provides advanced DI(Dependency Injection) experience in cloud-native.

Installation

Install Wire-Jacket by running:

go get github.com/bang9211/wire-jacket

and ensuring that $GOPATH/bin is added to your $PATH.

Example

Wire-Jacket example of ossicones. In this example, ossicones is simple blockchain package. It consisted of only 3 components: Config, Database, Blockchain.

Define simple two Interface, Implement.

type Database interface {
    Connect() bool
    Close() error   //necessary for Wire Jacket
}

type MySQL struct {
    cfg config.Config
}

func NewMySQL(cfg config.Config) Database {
    return &MySQL{cfg : cfg}
}

func (m *MySQL) Connect() error {
    address := m.cfg.GetString("address", "localhost:3306")
    ...
    return nil
}

func (m *MySQL) Close() error {
    return nil
}
type Blockchain interface {
    Init() error
    Close() error   //necessary for Wire Jacket
}

type Ossicones struct {
    db *Database
}

func NewOssicones(db Database) Blockchain {
    return &Ossicones{db : db}
}

func (o *Ossicones) Init() error {
    err := o.db.Connect()
    ...
    return nil
}

func (o *Ossicones) Close() error {
    return nil
}

Suppose there is MongoDB that implements Database Interface like MySQL. And Wire-Jacket has ViperConfig by default.

Then, there are 3 Interfaces and 4 Implements.

  • Database Interface - MySQL, MongoDB Implement
  • Blockchain Interface - Ossicones Implement
  • (Default) Config Interface - ViperConfig Implement

Database depends on config.Config. Blockchain depends on Database.

The pair of interface and implement called module in Wire-Jacket.

Wire-Jacket helps to replace implement of interface easy way. And close modules gracefully. So the modules are closable, have to implment Close().

1. Create wire.go with injectors.

package wire

func InjectMySQL(cfg config.Config) (Database, error) {
	wire.Build(NewMySQL)
	return nil, nil
}

func InjectMongoDB(cfg config.Config) (Databsae, error) {
    wire.Build(NewMongoDB)
    return nil, nil
}

func InjectOssicones(db Database) (Blockchain, error) {
	wire.Build(NewOssicones)
	return nil, nil
}

// key will use in app.conf
var Injectors map[string]interface{} = {"mysql" : InjectMySQL}
var EagerInjectors map[string]interface{} = {"ossicones" : InjectOssicones}

2. Generate wire_gen.go using wire.

wire wire.go

wire is compile-time DI. It can verify validity of DI in compile-time.

3. Create app.conf(default way)

# Specify module to use.
modules=mysql ossicones

# And you can add any config to use.
db_host=localhost
db_port=3306

Choose modules to use mysql, ossicones.

Database binds to MySQL, Blockchain binds to Ossicones.

4. Create wirejacket, Set injectors, Call DoWire().

wj := wirejacket.New().
    SetInjectors(wire.Injectors).
    SetEagerInjectors(wire.EagerInjectors)

// inject eager injectors.
wj.DoWire()

Except for eager injectors, injectors are loaded lazy by default.

Or If you call wj.GetModule() to get the module you need, all the dependencies of the module will be injected automatically. you don't need to call DoWire() in this case. It is not necessary to call DoWire().

Assume that there is mongodb like mysql as the implementation of Database.

If you want to change implement of Database to mongodb, Just modify modules in config and restart app.

modules=mongodb ossicones

Features

  • google/wire based IoC Container
  • Environment-variable based setting for cloud
  • Lazy Loading, Eager Loading

Why Wire-Jacket needs?

google/wire works statically because it performs DI at compile-time. This approach is great for pre-debugging of DI.

It is difficult to debug problems that occur at runtime like dependency injection in a cloud environment. So It can be usefully used in a cloud environment.

Wire-Jacket wraps google/wire in order to use google/wire appropriately for the cloud environment.

1. IoC (Inversion of Control) Container

google/wire just provides injecting and binding features, do not have an IoC container. IoC Container makes it easy to version up and replace modules. You can also make a Plan B and keep it. For example, DB Skip mode that does not use DB or emergency processing mode that does not actually connect with other nodes can be applied by replacing module and restarting.

And it helps not to use singleton as a global variable. Automatically maintains and recycles one singleton object.

2. Binding based environment-variable for cloud.

The Twelve-Factors recommends use environment variables for configuration. Because it's good in container, cloud environments. However, it is not efficient to express all configs as environment variables.

So, we adopted viper, which integrates most config formats with environment variables in go. By using viper, you can use various config file formats without worrying about conversion to environment variables even if it is not in env format like json, yaml, toml, etc.

In Wire-Jacket, modules to use set in config file. For example, if you use the MySQL DB implementation in your app and want to replace the implementation with MongoDB, you don't need to change the code.

just change MySQL to MongoDB in config and restart the app.

3. Modulization, Loose-Coupling.

Wirejacket uses the simple approach of injecting implement into the interface. This approach simplifies and allows the team leader or designer to define the interface required for the project and effectively divide the work. the each implementation can be integrated easily and replaced as a plug-in using the config file.

Owner
Youngtak Han
Have a little fun.
Youngtak Han
Similar Resources

A different approach to Go web frameworks

A different approach to Go web frameworks

Note: gongular recently updated, and if you are looking for the previous version it is tagged as v.1.0 gongular is an HTTP Server Framework for develo

Jan 7, 2023

webrpc is a schema-driven approach to writing backend services for modern Web apps and networks

webrpc is a schema-driven approach to writing backend services for modern Web apps and networks

webrpc is a schema-driven approach to writing backend servers for the Web. Write your server's api interface in a schema format of RIDL or JSON, and t

Jan 7, 2023

A simulated-annealing approach to solving a max-flow removal problem

A simulated-annealing approach to solving a max-flow removal problem

RESISTANCE IS FUTILE How to run: Install the latest version of golang to your computer (1.16?) Run a postgres instance on your computer attatched to p

Aug 26, 2022

Boilerplate for writing Go applications without framework using hexagonal application development approach

Boilerplate for writing Go applications without framework using hexagonal application development approach

Boilerplate for writing Go applications without framework using hexagonal application development approach

Dec 2, 2022

Two approach for solving common items problem using Golang

Compare Two Arrays For Common Items Given two seperate arrays of integers, create a function that take two arrays and check for common itemss. Example

Nov 28, 2021

Simple test driven approach in "GOLANG"

Simple test driven approach in

Testing in GOLANG Usage Only test go test -v Coverage go test -cover or go test -coverprofile=coverage.out go tool cover -html=coverage.out Benchmark

Dec 5, 2021

A hands-on approach for getting started with Go generics.

Go Generics the Hard Way This repository is a hands-on approach for getting started with Go generics: Prerequisites: how to install the prerequisites

Dec 27, 2022

Decks - A first approach in GoLang learning

Decks - Go Decks is a small project that I'm building to learn GoLang. My resour

Jan 12, 2022

This package attempts to use an elegant (although potentially inefficient) approach to streams in go.

This package attempts to use an elegant (although potentially inefficient) approach to streams in goThis package attempts to use an elegant (although potentially inefficient) approach to streams in go

Mar 24, 2022

Mob-code-server - Mob programming - a software development approach where the whole team works on the same thing

Mob-code-server - Mob programming - a software development approach where the whole team works on the same thing

For those times when you need a ready to use server with a little more horse pow

Feb 2, 2022

stratus is a cross-cloud identity broker that allows workloads with an identity issued by one cloud provider to exchange this identity for a workload identity issued by another cloud provider.

stratus is a cross-cloud identity broker that allows workloads with an identity issued by one cloud provider to exchange this identity for a workload identity issued by another cloud provider.

stratus stratus is a cross-cloud identity broker that allows workloads with an identity issued by one cloud provider to exchange this identity for a w

Dec 26, 2021

Cloud-Z gathers information and perform benchmarks on cloud instances in multiple cloud providers.

Cloud-Z Cloud-Z gathers information and perform benchmarks on cloud instances in multiple cloud providers. Cloud type, instance id, and type CPU infor

Jun 8, 2022

Contentrouter - Protect static content via Firebase Hosting with Cloud Run and Google Cloud Storage

contentrouter A Cloud Run service to gate static content stored in Google Cloud

Jan 2, 2022

This Go based project of Aadhyarupam Innovators demonstrate the code examples for building microservices, integration with cloud services (Google Cloud Firestore), application configuration management (Viper) etc.

This Go based project of Aadhyarupam Innovators demonstrate the code examples for building microservices, integration with cloud services (Google Cloud Firestore), application configuration management (Viper) etc.

Dec 22, 2022

RabbitMQ wire tap and swiss army knife

RabbitMQ wire tap and swiss army knife

rabtap - RabbitMQ wire tap Swiss army knife for RabbitMQ. Tap/Pub/Sub messages, create/delete/bind queues and exchanges, inspect broker. Contents Feat

Dec 28, 2022

RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

Gin Admin 基于 GIN + GORM + CASBIN + WIRE 实现的RBAC权限管理脚手架,目的是提供一套轻量的中后台开发框架,方便、快速的完成业务需求的开发。 特性 遵循 RESTful API 设计规范 & 基于接口的编程规范 基于 GIN 框架,提供了丰富的中间件支持(JWT

Dec 28, 2022

wire protocol for multiplexing connections or streams into a single connection, based on a subset of the SSH Connection Protocol

qmux qmux is a wire protocol for multiplexing connections or streams into a single connection. It is based on the SSH Connection Protocol, which is th

Dec 26, 2022

golang auto wire code generator

Go-AutoWire helps you to generate wire files with easy annotate 中文文档 this project is base on wire but it did simplify the wire usage and make wire muc

Dec 2, 2022

Wire: Automated Initialization in Go

Wire: Automated Initialization in Go Wire is a code generation tool that automates connecting components using dependency injection. Dependencies betw

Dec 10, 2021
Comments
  • Consider ViperConfig reads string with env

    Consider ViperConfig reads string with env

    In this example case,

    ossicones_explorer_server_template_path=${OSSICONES_SRC_HOME}/templates

    If there is no $OSSICONES_SRC_HOME, it specify just /template.

    No one wants to happen it.

Wire: Automated Initialization in Go

Wire: Automated Initialization in Go Wire is a code generation tool that automates connecting components using dependency injection. Dependencies betw

Dec 10, 2021
Experimental wire-format protobuf canonicalizer

wirepb This repository implements an experimental wire-format canonical string format for protocol buffer messages. Specifically, the wirepb.Canonical

Oct 25, 2022
Mgosniff: MongoDB Wire Protocol Analysis Tools

mgosniff - MongoDB Wire Protocol Analysis Tools Reference: MongoDB Wire Protocol

Feb 18, 2022
Jacket of spf13/viper: Simplified go configuration for wire-jacket.

Viper-Jacket: viper config for Wire-Jacket Jacket of spf13/viper: config for wire-jacket. Simplified env-based go configuration package using viper. b

Nov 18, 2021
provide api for cloud service like aliyun, aws, google cloud, tencent cloud, huawei cloud and so on

cloud-fitter 云适配 Communicate with public and private clouds conveniently by a set of apis. 用一套接口,便捷地访问各类公有云和私有云 对接计划 内部筹备中,后续开放,有需求欢迎联系。 开发者社区 开发者社区文档

Dec 20, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Dec 6, 2022
Obfuscate Go code by wrapping the Go toolchain

Obfuscate Go code by wrapping the Go toolchain.

Dec 31, 2022
Wrap contains a method for wrapping one Go error with another.

Note: this code is still in alpha stage. It works but it may change subtly in the near future, depending on what comes out of golang/go#52607. Wrap.Wi

Jun 27, 2022
Go package exposing a simple interface for executing commands, enabling easy mocking and wrapping of executed commands.

go-runner Go package exposing a simple interface for executing commands, enabling easy mocking and wrapping of executed commands. The Runner interface

Oct 18, 2022
"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Yandex Files

Website | Documentation | Download | Contributing | Changelog | Installation | Forum Rclone Rclone ("rsync for cloud storage") is a command-line progr

Jan 9, 2023