func StartMyApp(port int, dbName string) { var env Env.Env var g inject.Graph db, e := Data.NewDB(dbName) log.Println(e) err := g.Provide( &inject.Object{Value: &env}, &inject.Object{Value: db}, ) if err != nil { log.Fatalf("Error providing dependencies: ", err.Error()) } if err := g.Populate(); err != nil { log.Fatalf("Error providing dependencies: ", err.Error()) } routes := Api.Routes(env) routes.Run(fmt.Sprintf(":%v", port)) }
func TestObjectString(t *testing.T) { var g inject.Graph a := &TypeNestedStruct{} if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil { t.Fatal(err) } var c TypeForObjectString if err := g.Provide(&inject.Object{Value: &c}); err != nil { t.Fatal(err) } if err := g.Populate(); err != nil { t.Fatal(err) } var actual []string for _, o := range g.Objects() { actual = append(actual, fmt.Sprint(o)) } ensure.SameElements(t, actual, []string{ "*inject_test.TypeForObjectString", "*inject_test.TypeNestedStruct", "*inject_test.TypeNestedStruct named foo", "*inject_test.TypeAnswerStruct", }) }
func TestInjectLogging() { g := inject.Graph{ Logger: &logger{ Expected: []string{ "provided *main.TypeForLoggingCreated named name_for_logging", "provided *main.TypeForLogging", "provided embedded *main.TypeForLoggingEmbedded", "created *main.TypeForLoggingCreated", "assigned newly created *main.TypeForLoggingCreated to field TypeForLoggingCreated in *main.TypeForLogging", "assigned existing *main.TypeForLoggingCreated to field TypeForLoggingCreated in *main.TypeForLoggingEmbedded", "assigned *main.TypeForLoggingCreated named name_for_logging to field TypeForLoggingCreatedNamed in *main.TypeForLoggingEmbedded", "made map for field Map in *main.TypeForLoggingEmbedded", "assigned existing *main.TypeForLoggingCreated to interface field TypeForLoggingInterface in *main.TypeForLoggingEmbedded", }, }, } var v TypeForLogging err := g.Provide( &inject.Object{Value: &TypeForLoggingCreated{}, Name: "name_for_logging"}, &inject.Object{Value: &v}, ) if err != nil { fmt.Println(err) } if err := g.Populate(); err != nil { fmt.Println(err) } }
func TestObjectString() { var g inject.Graph a := &TypeNestedStruct{} if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil { fmt.Println(err) } var c TypeForObjectString if err := g.Provide(&inject.Object{Value: &c}); err != nil { fmt.Println(err) } if err := g.Populate(); err != nil { fmt.Println(err) } a.A.answer = 100 fmt.Printf("c.A.A = %#v, c.B.A = %#v\n", c.A.A, c.B.A) var actual []string for _, o := range g.Objects() { fmt.Printf("%#v\n", o) actual = append(actual, fmt.Sprint(o)) } //fmt.Printf("%#v \n", actual) }
func newHarnessInternal(url string, s stopper, t testing.TB) *Harness { replicaSet := ReplicaSet{ Addrs: url, PortStart: 2000, PortEnd: 3000, MaxConnections: 5, MinIdleConnections: 5, ServerIdleTimeout: 5 * time.Minute, ServerClosePoolSize: 5, ClientIdleTimeout: 5 * time.Minute, MaxPerClientConnections: 250, GetLastErrorTimeout: 5 * time.Minute, MessageTimeout: time.Minute, } log := tLogger{TB: t} var graph inject.Graph err := graph.Provide( &inject.Object{Value: &log}, &inject.Object{Value: &replicaSet}, &inject.Object{Value: &stats.HookClient{}}, ) ensure.Nil(t, err) ensure.Nil(t, graph.Populate()) objects := graph.Objects() ensure.Nil(t, startstop.Start(objects, &log)) return &Harness{ T: t, Stopper: s, ReplicaSet: &replicaSet, Graph: &graph, Log: &log, } }
func (p FBInjectInstanceInitializer) Initialize(instance interface{}, typeName string) (interface{}, error) { var g inject.Graph if err := g.Provide(&inject.Object{Value: instance}); err != nil { return nil, err } if entry := p.initializers[typeName]; entry != nil { for _, v := range entry.dependencies { resolved, e1 := godi.Resolve(v) if e1 != nil { return nil, e1 } obj := inject.Object{Value: resolved} e2 := g.Provide(&obj) if e2 != nil { return nil, e2 } } } // construct the instance. // if e3 := g.Populate(); e3 != nil { return nil, e3 } return instance, nil }
func TestProvideWithFields(t *testing.T) { var g inject.Graph a := &TypeAnswerStruct{} err := g.Provide(&inject.Object{Value: a, Fields: map[string]*inject.Object{}}) ensure.NotNil(t, err) ensure.DeepEqual(t, err.Error(), "fields were specified on object *inject_test.TypeAnswerStruct when it was provided") }
func initiateTests() { var router routers.Router var graph inject.Graph setupTestData() db := data.NewJsonDB("../data/testing/testingDB.json") if err := graph.Provide( &inject.Object{Value: db}, &inject.Object{Value: repositories.NewCharacterRepository()}, &inject.Object{Value: &router}); err != nil { log.Fatalf("Error providing dependencies: ", err.Error()) } if err := graph.Populate(); err != nil { log.Fatalf("Error populating dependencies: ", err.Error()) } n := negroni.Classic() n.UseHandler(router.NewRouter()) ts = httptest.NewServer(n) }
// NewApp constructs an new App instance from the provided config. func NewApp(config config.Config, migrateFlag bool) (app *App, err error) { var g inject.Graph var driver db.Driver switch config.Database.Type { case "mysql": driver = &mysql.Driver{} case "postgres": driver = &postgres.Driver{} default: return nil, fmt.Errorf("%s database has no driver", config.Database.Type) } err = driver.Init(config.Database.URL) if err != nil { return } entityManager := db.NewEntityManager(driver) repository := db.NewRepository(driver) if migrateFlag { var migrationsApplied int migrationsApplied, err = driver.MigrateUp("compliance") if err != nil { return } log.Info("Applied migrations: ", migrationsApplied) os.Exit(0) return } requestHandler := handlers.RequestHandler{} err = g.Provide( &inject.Object{Value: &requestHandler}, &inject.Object{Value: &config}, &inject.Object{Value: &entityManager}, &inject.Object{Value: &repository}, &inject.Object{Value: &crypto.SignerVerifier{}}, &inject.Object{Value: &stellartoml.Resolver{}}, &inject.Object{Value: &federation.Resolver{}}, &inject.Object{Value: &http.Client{}}, ) if err != nil { log.Fatal("Injector: ", err) } if err := g.Populate(); err != nil { log.Fatal("Injector: ", err) } app = &App{ config: config, requestHandler: requestHandler, } return }
func Start(port int, fileLocation string) { var router routers.Router var graph inject.Graph // Create database db := data.NewJsonDB(fileLocation) // Setup DI if err := graph.Provide( &inject.Object{Value: db}, &inject.Object{Value: repositories.NewCharacterRepository()}, &inject.Object{Value: &router}); err != nil { log.Fatalf("Error providing dependencies: ", err.Error()) } if err := graph.Populate(); err != nil { log.Fatalf("Error populating dependencies: ", err.Error()) } n := negroni.Classic() n.UseHandler(router.NewRouter()) err := http.ListenAndServe(fmt.Sprintf(":%v", port), n) if err != nil { panic("Error: " + err.Error()) } }
func TestProvideNonPointer() { var g inject.Graph var i *int err := g.Provide(&inject.Object{Value: i}) fmt.Println(err) }
func ProvideWithFields() { var g inject.Graph a := &TypeAnswerStruct{} err := g.Provide(&inject.Object{Value: a, Fields: map[string]*inject.Object{}}) fmt.Println(err) //ensure.NotNil(glog.Fatal, err) //ensure.DeepEqual(fmt, err.Error(), "fields were specified on object *inject_test.TypeAnswerStruct when it was provided") }
func TestProvideTwoOfTheSame() { var g inject.Graph a := TypeAnswerStruct{} err := g.Provide(&inject.Object{Value: &a}) fmt.Println(err) err = g.Provide(&inject.Object{Value: &a}) fmt.Println(err) }
func TestInjectNamedTwoSatisfyInterface() { var g inject.Graph var v TypeInjectNamedTwoSatisfyInterface if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil { fmt.Println(err) } err := g.Populate() fmt.Println(err) }
func Main() error { messageTimeout := flag.Duration("message_timeout", 2*time.Minute, "timeout for one message to be proxied") clientIdleTimeout := flag.Duration("client_idle_timeout", 60*time.Minute, "idle timeout for client connections") getLastErrorTimeout := flag.Duration("get_last_error_timeout", time.Minute, "timeout for getLastError pinning") maxConnections := flag.Uint("max_connections", 100, "maximum number of connections per mongo") portStart := flag.Int("port_start", 6000, "start of port range") portEnd := flag.Int("port_end", 6010, "end of port range") addrs := flag.String("addrs", "localhost:27017", "comma separated list of mongo addresses") flag.Parse() replicaSet := dvara.ReplicaSet{ Addrs: *addrs, PortStart: *portStart, PortEnd: *portEnd, MessageTimeout: *messageTimeout, ClientIdleTimeout: *clientIdleTimeout, GetLastErrorTimeout: *getLastErrorTimeout, MaxConnections: *maxConnections, } var statsClient stats.HookClient var log stdLogger var graph inject.Graph err := graph.Provide( &inject.Object{Value: &log}, &inject.Object{Value: &replicaSet}, &inject.Object{Value: &statsClient}, ) if err != nil { return err } if err := graph.Populate(); err != nil { return err } objects := graph.Objects() // Temporarily setup the metrics against a test registry. gregistry := gangliamr.NewTestRegistry() for _, o := range objects { if rmO, ok := o.Value.(registerMetrics); ok { rmO.RegisterMetrics(gregistry) } } if err := startstop.Start(objects, &log); err != nil { return err } defer startstop.Stop(objects, &log) ch := make(chan os.Signal, 2) signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT) <-ch signal.Stop(ch) return nil }
func main() { // command line flags confFile := flag.String("conf", "emerald.conf", "location of config-file") flag.Parse() conf := core.LoadConfiguration(*confFile) var app core.EmeraldApp mongoService := mongo.NewService(&conf) ircClient := irc.NewClient() var g inject.Graph err := g.Provide( &inject.Object{Value: &conf}, &inject.Object{Value: &app}, &inject.Object{Value: mongoService}, &inject.Object{Value: ircClient}, ) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := g.Populate(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } //setup gin gin.SetMode(gin.ReleaseMode) router := gin.New() //Middlewares // router.Use(gin.Logger()) router.Use(gin.Recovery()) //static files router.Static("/assets", "./assets") router.StaticFile("/", "./assets/index.html") //register all controllers app.AddControllers(router) //Start all jobs app.StartJobs() // Listen and server on 0.0.0.0:8080 addr := fmt.Sprintf(":%d", conf.Port) log.Printf("Emerald started port %v\n", addr) fmt.Printf("Emerald started port %v\n", addr) err = router.Run(addr) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
func TestProvideTwoWithTheSameName() { var g inject.Graph const name = "foo" a := TypeAnswerStruct{} err := g.Provide(&inject.Object{Value: &a, Name: name}) fmt.Println(err) err = g.Provide(&inject.Object{Value: &a, Name: name}) fmt.Println(err) }
func Main() error { messageTimeout := flag.Duration("message_timeout", 2*time.Minute, "timeout for one message to be proxied") clientIdleTimeout := flag.Duration("client_idle_timeout", 60*time.Minute, "idle timeout for client connections") serverIdleTimeout := flag.Duration("server_idle_timeout", 1*time.Hour, "idle timeout for server connections") serverClosePoolSize := flag.Uint("server_close_pool_size", 100, "number of goroutines that will handle closing server connections") getLastErrorTimeout := flag.Duration("get_last_error_timeout", time.Minute, "timeout for getLastError pinning") maxPerClientConnections := flag.Uint("max_per_client_connections", 100, "maximum number of connections per client") maxConnections := flag.Uint("max_connections", 100, "maximum number of connections per mongo") portStart := flag.Int("port_start", 6000, "start of port range") portEnd := flag.Int("port_end", 6010, "end of port range") addrs := flag.String("addrs", "localhost:27017", "comma separated list of mongo addresses") flag.Parse() replicaSet := dvara.ReplicaSet{ Addrs: *addrs, PortStart: *portStart, PortEnd: *portEnd, MessageTimeout: *messageTimeout, ClientIdleTimeout: *clientIdleTimeout, ServerIdleTimeout: *serverIdleTimeout, ServerClosePoolSize: *serverClosePoolSize, GetLastErrorTimeout: *getLastErrorTimeout, MaxConnections: *maxConnections, MaxPerClientConnections: *maxPerClientConnections, } var statsClient stats.HookClient var log stdLogger var graph inject.Graph err := graph.Provide( &inject.Object{Value: &log}, &inject.Object{Value: &replicaSet}, &inject.Object{Value: &statsClient}, ) if err != nil { return err } if err := graph.Populate(); err != nil { return err } objects := graph.Objects() if err := startstop.Start(objects, &log); err != nil { return err } defer startstop.Stop(objects, &log) ch := make(chan os.Signal, 2) signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT) <-ch signal.Stop(ch) return nil }
func Injector(params ...interface{}) (err error) { var g inject.Graph for _, v := range params { if err = g.Provide(&inject.Object{Value: v}); err != nil { return } } if err = g.Populate(); err != nil { return } return }
func TestForSameNameButDifferentPackage(t *testing.T) { var g inject.Graph err := g.Provide( &inject.Object{Value: &injecttesta.Foo{}}, &inject.Object{Value: &injecttestb.Foo{}}, ) if err != nil { t.Fatal(err) } if err := g.Populate(); err != nil { t.Fatal(err) } }
func TestProvideNonPointerStruct(t *testing.T) { var g inject.Graph var i *int err := g.Provide(&inject.Object{Value: i}) if err == nil { t.Fatal("expected error") } const msg = "expected unnamed object value to be a pointer to a struct but got type *int with value <nil>" if err.Error() != msg { t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error()) } }
func injectTest() { // Typically an application will have exactly one object graph, and // you will create it and use it within a main function: var g inject.Graph // We provide our graph two "seed" objects, one our empty // HomePlanetRenderApp instance which we're hoping to get filled out, // and second our DefaultTransport to satisfiy our HTTPTransport // dependency. We have to provide the DefaultTransport because the // dependency is defined in terms of the http.RoundTripper interface, // and since it is an interface the library cannot create an instance // for it. Instead it will use the given DefaultTransport to satisfy // the dependency since it implements the interface: var a HomePlanetRenderApp err := g.Provide( &inject.Object{Value: &a}, &inject.Object{Value: http.DefaultTransport}, ) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } // Here the Populate call is creating instances of NameAPI & // PlanetAPI, and setting the HTTPTransport on both to the // http.DefaultTransport provided above: if err := g.Populate(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Printf("a = %#v\n", a) fmt.Printf("http.DefaultTransport = %#v\n", http.DefaultTransport) for _, o := range g.Objects() { fmt.Printf(" = %#v\n", o) } // There is a shorthand API for the simple case which combines the // three calls above is available as inject.Populate: // // inject.Populate(&a, http.DefaultTransport) // // The above API shows the underlying API which also allows the use of // named instances for more complex scenarios. fmt.Println(a.Render(42)) // Output: Spock is from the planet Vulcan. }
func TestCompleteNamedProvides(t *testing.T) { var g inject.Graph var v struct { A *TypeAnswerStruct `inject:""` } if err := g.Provide(&inject.Object{Value: &v, Complete: true, Name: "foo"}); err != nil { t.Fatal(err) } if err := g.Populate(); err != nil { t.Fatal(err) } if v.A != nil { t.Fatal("v.A was not nil") } }
//Map map objects func (p *Engine) Map(inj *inject.Graph) error { enc, err := NewAesHmacEncryptor(Secret(120, 32), Secret(210, 32)) if err != nil { return err } return inj.Provide( &inject.Object{Value: enc}, &inject.Object{Value: Secret(320, 32), Name: "jwt.key"}, &inject.Object{Value: crypto.SigningMethodHS512, Name: "jwt.method"}, &inject.Object{Value: "cache", Name: "cache.prefix"}, &inject.Object{Value: "ga2", Name: "oauth2.google.state"}, ) }
//IocAction ioc action func IocAction(fn func(*cli.Context, *inject.Graph) error) cli.ActionFunc { return Action(func(ctx *cli.Context) error { var inj inject.Graph logger := Logger() if !IsProduction() { inj.Logger = logger } db, err := OpenDatabase() if err != nil { return err } rep := OpenRedis() wfg := viper.GetStringMapString("workers.config") wfg["server"] = fmt.Sprintf( "%s:%d", viper.GetString("redis.host"), viper.GetInt("redis.port")) wfg["database"] = viper.GetString("redis.db") workers.Configure(wfg) i1n := i18n.I18n{Locales: make(map[string]map[string]string)} if err := inj.Provide( &inject.Object{Value: logger}, &inject.Object{Value: db}, &inject.Object{Value: rep}, &inject.Object{Value: &i18n.DatabaseProvider{}}, &inject.Object{Value: &i1n}, ); err != nil { return err } Loop(func(en Engine) error { if e := en.Map(&inj); e != nil { return e } return inj.Provide(&inject.Object{Value: en}) }) if err := inj.Populate(); err != nil { return err } if err := i1n.Load("locales"); err != nil { return err } return fn(ctx, &inj) }) }
func TestInjectNamedTwoSatisfyInterface(t *testing.T) { var g inject.Graph var v TypeInjectNamedTwoSatisfyInterface if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil { t.Fatal(err) } err := g.Populate() if err == nil { t.Fatal("was expecting error") } const msg = "found two assignable values for field Answerable in type *inject_test.TypeInjectNamedTwoSatisfyInterface. one type *inject_test.TypeAnswerStruct with value &{0 0} and another type *inject_test.TypeNestedStruct with value <*inject_test.TypeNestedStruct Value>" if err.Error() != msg { t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error()) } }
func TestInvalidNamedInstanceType() { var g inject.Graph a := &TypeAnswerStruct{} if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil { fmt.Println(err) } var c TypeWithInvalidNamedType if err := g.Provide(&inject.Object{Value: &c}); err != nil { fmt.Println(err) } err := g.Populate() fmt.Println(err) }
func TestInjectNamedOnPrivateInterfaceField(t *testing.T) { var g inject.Graph var v TypeWithInjectNamedOnPrivateInterfaceField if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil { t.Fatal(err) } err := g.Populate() if err == nil { t.Fatal("was expecting error") } const msg = "inject requested on unexported field a in type *inject_test.TypeWithInjectNamedOnPrivateInterfaceField" if err.Error() != msg { t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error()) } }
func TestGraphObjects() { var g inject.Graph err := g.Provide( //&inject.Object{Value: &TypeNestedStruct{}, Name: "foo"}, &inject.Object{Value: &TypeForGraphObjects{}}, ) fmt.Println(err) if err := g.Populate(); err != nil { fmt.Println(err) } var actual []string for _, o := range g.Objects() { actual = append(actual, fmt.Sprint(o)) } fmt.Printf("%#v\n", actual) }
func TestNoAddrsGiven(t *testing.T) { t.Parallel() replicaSet := ReplicaSet{MaxConnections: 1} var log nopLogger var graph inject.Graph err := graph.Provide( &inject.Object{Value: &log}, &inject.Object{Value: &replicaSet}, &inject.Object{Value: &stats.HookClient{}}, ) ensure.Nil(t, err) ensure.Nil(t, graph.Populate()) objects := graph.Objects() err = startstop.Start(objects, &log) if err != errNoAddrsGiven { t.Fatalf("did not get expected error, got: %s", err) } }