Documentation ¶
Overview ¶
Package injekt provides a pluggable service injector for any project or framework. Service injection is achieved by wrapping a custom function (with services as parameters) with the required function.
http.Handler example:
Write custom function. `session` will be injected as well as specified parameters of the required function.
func sessionInfo(w http.ResponseWriter, session *Session) { if session == nil { // show login page } ... }
Wrap custom function. This returns an `interface{}` that can be asserted to the required function type.
func main(){ var h http.HandlerFunc inj := injekt.New(h) ... http.HandleFunc("/", inj.Wrap(sessionInfo).(http.HandlerFunc)) }
Register services before function is executed.
session := ... inj.Register(session)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Injector ¶
type Injector struct {
// contains filtered or unexported fields
}
Injector is a service injector.
func New ¶
func New(funcType interface{}) *Injector
New creates a new Injector. funcType is value of the required function type to wrap to.
// http.HandlerFunc as required function. var f http.HandlerFunc injekt.New(f) // func(c *mypackge.Context) as required function. injekt.New(func(c *mypackge.Context){})
func (*Injector) Register ¶
func (inj *Injector) Register(service interface{})
Register registers a new service. Services are identifiable by their types. Multiple services of same type should be grouped into a struct, and the struct should be registered instead.
func (Injector) Wrap ¶
func (inj Injector) Wrap(f interface{}) interface{}
Wrap wraps f and return a function compatible with the required function. f must be a function, otherwise a panic occurs.
If f returns values, f and the required function must have same return types to get desired behaviour. If any of the services passed as parameters to f is not registered, empty value of the type will be passed.
// http.HandlerFunc required function. http.HandleFunc("/", inj.Wrap(myFunc).(http.HandlerFunc)) // func(c *mypackage.Context) required function and custom router. myRouter.Handle("/", inj.Wrap(myFunc).(func(c *mypackage.Context)))