Socket
Book a DemoInstallSign in
Socket

github.com/dc0d/sector

Package Overview
Dependencies
Alerts
File Explorer
Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

github.com/dc0d/sector

v0.0.0-20170306121114-96dd9ace40c2
Source
Go
Version published
Created
Source

sector

License MIT GoDoc Go Report Card Build Status codecov

sector - for Simple Injector - provides a Dependency Injection mechanism for Go.

Put it simply, sector fills pointers with values come from factories. So we have the factory - the constructor (role) - and the injector.

A factory implements the Factory interface. In it's simplest form, it's just a function with this signature, func(interface{}) bool and uses the Go's type switch to fill the pointers:

func myFactory(ptr interface{}) bool {
	switch x := ptr.(type) {
	case *int:
		*x = 1001
	case *string:
		*x = `injected string`
	case *Trait:
		buffer := Trait{}
		*x = buffer
	case *Data:
		buffer := Data{}
		*x = buffer
	case *map[string]interface{}:
		*x = make(map[string]interface{})
		(*x)[`asset`] = `another injected string`
	case *SI:
		v := SIO{`yet another injected string`}
		*x = &v
	case *[]int:
		*x = []int{1, 2, 3}
	default:
                // this factory does not fill pointers of this type
		return false
	}

	return true
}

Then we use this factory in our injector to fill in the fields of a struct.

dj := NewInjector(FactoryFunc(genericFactory))

Now we use this injector to inject desired values into struct's fields.

var s Sample
dj.Inject(&s)

Fields that are tagged with inject:"+" will get filled with proper value from the factory. Fields tagged with inject:"*" will get filled recursively down the tree.

type Sample struct {
	Trait `inject:"*"`      // inject field, recursively, all down the data tree  

	N  int    `inject:"+"`  // inject field
	S  string `inject:"+"`
	D  Data   `inject:"*"`
	NL []int  `inject:"+"`

	Map     map[string]interface{} `inject:"+"`
	DataPtr *Data                  `inject:"*"`

	SI SI `inject:"+"`
}

It is also possible to inject arguments of a function using the Invoke method.

FAQs

Package last updated on 06 Mar 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.