コード例 #1
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
func TestTwoNamedInstances(t *testing.T) {
	var g inject.Graph
	a := &TypeAnswerStruct{}
	b := &TypeAnswerStruct{}
	if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil {
		t.Fatal(err)
	}

	if err := g.Provide(&inject.Object{Value: b, Name: "bar"}); err != nil {
		t.Fatal(err)
	}

	var c struct {
		A *TypeAnswerStruct `inject:"foo"`
		B *TypeAnswerStruct `inject:"bar"`
	}
	if err := g.Provide(&inject.Object{Value: &c}); err != nil {
		t.Fatal(err)
	}

	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}

	if c.A != a {
		t.Fatal("did not find expected c.A")
	}
	if c.B != b {
		t.Fatal("did not find expected c.B")
	}
}
コード例 #2
0
ファイル: app.go プロジェクト: stellar/bridge-server
// 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
}
コード例 #3
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
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",
	})
}
コード例 #4
0
ファイル: server.go プロジェクト: mattdotmatt/bigstar
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())
	}
}
コード例 #5
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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)

}
コード例 #6
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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)
	}
}
コード例 #7
0
ファイル: Server.go プロジェクト: FanszHub/test-site
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))
}
コード例 #8
0
ファイル: fbinject.go プロジェクト: shawnburke/godi
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
}
コード例 #9
0
ファイル: common_test.go プロジェクト: CrocdileChan/dvara
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,
	}
}
コード例 #10
0
ファイル: server_test.go プロジェクト: mattdotmatt/bigstar
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)
}
コード例 #11
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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)
}
コード例 #12
0
ファイル: main.go プロジェクト: kahoona77/emerald
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)
	}
}
コード例 #13
0
ファイル: main.go プロジェクト: Vungle/dvara
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
}
コード例 #14
0
ファイル: main.go プロジェクト: CrocdileChan/dvara
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
}
コード例 #15
0
ファイル: inject.go プロジェクト: go-rut/utils
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
}
コード例 #16
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
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)
	}
}
コード例 #17
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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.
}
コード例 #18
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
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")
	}
}
コード例 #19
0
ファイル: run.go プロジェクト: itpkg/chaos
//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)
	})
}
コード例 #20
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
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())
	}
}
コード例 #21
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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)

}
コード例 #22
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
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())
	}
}
コード例 #23
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
func TestCompleteProvides() {
	var g inject.Graph
	var v struct {
		A *TypeAnswerStruct `inject:""`
		i int
	}

	if err := g.Provide(&inject.Object{Value: &v, Complete: true, Name: "foo"}); err != nil {
		fmt.Println(err)
	}

	if err := g.Populate(); err != nil {
		fmt.Println(err)
	}

	fmt.Println(v)

}
コード例 #24
0
ファイル: proxy_test.go プロジェクト: wptad/dvara
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)
	}
}
コード例 #25
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
func TestInjectWithNonpointerStructValue(t *testing.T) {
	var v TypeWithNonpointerStructValue
	var g inject.Graph
	if err := g.Provide(&inject.Object{Value: &v}); err != nil {
		t.Fatal(err)
	}
	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}
	if v.Inline.A == nil {
		t.Fatal("v.Inline.A is nil")
	}
	n := len(g.Objects())
	if n != 3 {
		t.Fatalf("expected 3 object in graph, got %d", n)
	}

}
コード例 #26
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
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)
}
コード例 #27
0
ファイル: main.go プロジェクト: cep21/goinjection-examples
func main() {
	dconf := distconf.New([]distconf.Reader{distconf.Env()})

	var graph inject.Graph
	var server app.Server

	if err := graph.Provide(
		&inject.Object{
			Value: &timekeeper.RealTime{},
		},
		&inject.Object{
			Value: log.DefaultLogger,
		},
		&inject.Object{
			Value: http.NewServeMux(),
		},
		&inject.Object{
			Value: &app.StrictCheck{
				Username: "******",
				Password: "******",
			},
		},
		&inject.Object{
			Value: dconf,
		},
		&inject.Object{
			Value: &server,
		},
	); err != nil {
		panic(err)
	}
	if err := graph.Populate(); err != nil {
		panic(err)
	}

	logger := server.Logger
	logger.Log("Setting up")
	if err := server.Setup(); err != nil {
		logger.Log("Cannot setup!")
		panic(err)
	}
	err := server.Start(context.Background())
	fmt.Println(err)
}
コード例 #28
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
func TestErrorOnNonPointerNamedInject(t *testing.T) {
	var g inject.Graph
	if err := g.Provide(&inject.Object{Name: "foo", Value: 42}); err != nil {
		t.Fatal(err)
	}

	var v TypeWithNonPointerNamedInject
	if err := g.Provide(&inject.Object{Value: &v}); err != nil {
		t.Fatal(err)
	}

	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}

	if v.A != 42 {
		t.Fatalf("expected v.A = 42 but got %d", v.A)
	}
}
コード例 #29
0
ファイル: inject_test.go プロジェクト: stellar/bridge-server
func TestForNamedWithUnnamed(t *testing.T) {
	var g inject.Graph
	var v TypeForNamedWithUnnamed

	err := g.Provide(
		&inject.Object{Value: &v, Name: "foo"},
	)
	if err != nil {
		t.Fatal(err)
	}
	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}
	if v.TypeForNamedWithUnnamedDepFirst == nil {
		t.Fatal("expected TypeForNamedWithUnnamedDepFirst to be populated")
	}
	if v.TypeForNamedWithUnnamedDepFirst.TypeForNamedWithUnnamedDepSecond == nil {
		t.Fatal("expected TypeForNamedWithUnnamedDepSecond to be populated")
	}
}
コード例 #30
0
ファイル: injecttest.go プロジェクト: uileyar/helloworld
func TestInjectWithNonpointerStructValue() {
	var v TypeWithNonpointerStructValue
	var g inject.Graph
	if err := g.Provide(&inject.Object{Value: &v}); err != nil {
		fmt.Println(err)
	}
	if err := g.Populate(); err != nil {
		fmt.Println(err)
	}
	if v.Inline.A == nil {
		fmt.Println("v.Inline.A is nil")
	}
	//n := len(g.Objects())

	tek := g.Objects()
	for n, value := range tek {

		fmt.Printf("n = %d, value = %#v\n", n, value)
	}

}