コード例 #1
0
ファイル: db.go プロジェクト: micro/platform
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.db"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.String("database_service_namespace")) > 0 {
		db.DBServiceNamespace = ctx.String("database_service_namespace")
	}

	proto.RegisterDBHandler(service.Server(), new(handler.DB))

	if err := db.Init(service.Client().Options().Selector); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
コード例 #2
0
ファイル: hipchat.go プロジェクト: Zerak/micro
func (h *hipchatInput) Init(ctx *cli.Context) error {
	username := ctx.String("hipchat_username")
	password := ctx.String("hipchat_password")
	server := ctx.String("hipchat_server")
	debug := ctx.Bool("hipchat_debug")

	if len(username) == 0 {
		return errors.New("require username")
	}

	if len(password) == 0 {
		return errors.New("require password")
	}

	if len(server) == 0 {
		return errors.New("require server")
	}

	h.username = username
	h.password = password
	h.server = server
	h.debug = debug

	return nil
}
コード例 #3
0
ファイル: router.go プロジェクト: micro/go-plugins
func (r *router) Init(ctx *cli.Context) error {
	// TODO: Make this more configurable and add more sources
	var conf config.Config

	if c := ctx.String("config_source"); len(c) == 0 && r.opts.Config == nil {
		return errors.New("config source must be defined")
	} else if len(c) > 0 {
		var source config.Source

		switch c {
		case "platform":
			source = config.NewSource()
		case "file":
			fileName := DefaultFile

			parts := strings.Split(c, ":")

			if len(parts) > 1 {
				fileName = parts[1]
			}

			source = file.NewSource(config.SourceName(fileName))
		default:
			return errors.New("Unknown config source " + c)
		}

		conf = config.NewConfig(config.WithSource(source))
	} else {
		conf = r.opts.Config
	}

	go r.run(conf)

	return nil
}
コード例 #4
0
ファイル: slack.go プロジェクト: Zerak/micro
func (p *slackInput) Init(ctx *cli.Context) error {
	debug := ctx.Bool("slack_debug")
	token := ctx.String("slack_token")

	if len(token) == 0 {
		return errors.New("missing slack token")
	}

	p.debug = debug
	p.token = token

	return nil
}
コード例 #5
0
ファイル: main.go プロジェクト: yaiio/go-micro-helloworld
func runClient(service micro.Service, c *cli.Context) {
	// Create new greeter client
	greeter := greeterProto.NewGreeterClient("greeter", service.Client())

	name := "World"

	if flagName := c.String("name"); flagName != "" {
		name = flagName
	}

	// Call the greeter
	rsp, err := greeter.Hello(context.TODO(), &greeterProto.HelloRequest{Name: name})
	if err != nil {
		fmt.Println(err)
		return
	}

	// Print response
	fmt.Println(rsp.Greeting)
}
コード例 #6
0
ファイル: kv.go プロジェクト: micro/platform
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.kv"),
		micro.Version("latest"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
		micro.Flags(),
	)

	opts := []kv.Option{
		kv.Client(service.Client()),
		kv.Server(service.Server()),
	}

	if len(ctx.String("namespace")) > 0 {
		opts = append(opts, kv.Namespace(ctx.String("namespace")))
	}

	keyval := kv.NewKV(opts...)
	defer keyval.Close()

	service.Server().Init(server.WrapHandler(func(fn server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) error {
			ctx = kv.NewContext(ctx, keyval)
			return fn(ctx, req, rsp)
		}
	}))

	proto.RegisterStoreHandler(service.Server(), new(handler.Store))

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
コード例 #7
0
ファイル: bot.go プロジェクト: xiaoxiaoyijian/micro
func run(ctx *cli.Context) {
	// Parse flags
	if len(ctx.String("inputs")) == 0 {
		log.Println("[bot] no inputs specified")
		os.Exit(1)
	}

	inputs := strings.Split(ctx.String("inputs"), ",")
	if len(inputs) == 0 {
		log.Println("[bot] no inputs specified")
		os.Exit(1)
	}

	ios := make(map[string]input.Input)
	cmds := make(map[string]command.Command)

	// create built in commands
	for pattern, cmd := range commands {
		cmds[pattern] = cmd(ctx)
	}

	// take other commands
	for pattern, cmd := range command.Commands {
		if c, ok := cmds[pattern]; ok {
			log.Printf("[bot] command %s already registered for pattern %s\n", c.String(), pattern)
			continue
		}
		// register command
		cmds[pattern] = cmd
	}

	// Parse inputs
	for _, io := range inputs {
		i, ok := input.Inputs[io]
		if !ok {
			log.Printf("[bot] input %s not found\n", i)
			os.Exit(1)
		}
		ios[io] = i
	}

	// Start bot
	b := newBot(ctx, ios, cmds)

	if err := b.start(); err != nil {
		log.Println("error starting bot", err)
		os.Exit(1)
	}

	// setup service
	service := micro.NewService(
		micro.Name("go.micro.bot"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	// Stop bot
	if err := b.stop(); err != nil {
		log.Println("error stopping bot", err)
	}
}
コード例 #8
0
ファイル: cmd.go プロジェクト: lucmichalski/go-micro
func (c *cmd) Before(ctx *cli.Context) error {
	// Due to logger issues with glog, we need to do this
	os.Args = os.Args[:1]
	flag.Set("logtostderr", fmt.Sprintf("%v", ctx.Bool("logtostderr")))
	flag.Set("alsologtostderr", fmt.Sprintf("%v", ctx.Bool("alsologtostderr")))
	flag.Set("stderrthreshold", ctx.String("stderrthreshold"))
	flag.Set("log_backtrace_at", ctx.String("log_backtrace_at"))
	flag.Set("log_dir", ctx.String("log_dir"))
	flag.Set("vmodule", ctx.String("vmodule"))
	flag.Set("v", ctx.String("v"))
	flag.Parse()

	// If flags are set then use them otherwise do nothing
	var serverOpts []server.Option
	var clientOpts []client.Option

	// Set the broker
	if len(ctx.String("broker")) > 0 {
		if b, ok := c.opts.Brokers[ctx.String("broker")]; ok {
			n := b(strings.Split(ctx.String("broker_address"), ","))
			*c.opts.Broker = n
		} else {
			return fmt.Errorf("Broker %s not found", ctx.String("broker"))
		}

		serverOpts = append(serverOpts, server.Broker(*c.opts.Broker))
		clientOpts = append(clientOpts, client.Broker(*c.opts.Broker))

	}

	// Set the registry
	if len(ctx.String("registry")) > 0 {
		if r, ok := c.opts.Registries[ctx.String("registry")]; ok {
			n := r(strings.Split(ctx.String("registry_address"), ","))
			*c.opts.Registry = n
		} else {
			return fmt.Errorf("Registry %s not found", ctx.String("registry"))
		}

		serverOpts = append(serverOpts, server.Registry(*c.opts.Registry))
		clientOpts = append(clientOpts, client.Registry(*c.opts.Registry))

		(*c.opts.Selector).Init(selector.Registry(*c.opts.Registry))
		clientOpts = append(clientOpts, client.Selector(*c.opts.Selector))

		(*c.opts.Broker).Init(broker.Registry(*c.opts.Registry))
	}

	// Set the selector
	if len(ctx.String("selector")) > 0 {
		if s, ok := c.opts.Selectors[ctx.String("selector")]; ok {
			n := s(selector.Registry(*c.opts.Registry))
			*c.opts.Selector = n
		} else {
			return fmt.Errorf("Selector %s not found", ctx.String("selector"))
		}

		// No server option here. Should there be?
		clientOpts = append(clientOpts, client.Selector(*c.opts.Selector))
	}

	// Set the transport
	if len(ctx.String("transport")) > 0 {
		if t, ok := c.opts.Transports[ctx.String("transport")]; ok {
			n := t(strings.Split(ctx.String("transport_address"), ","))
			*c.opts.Transport = n
		} else {
			return fmt.Errorf("Transport %s not found", ctx.String("transport"))
		}

		serverOpts = append(serverOpts, server.Transport(*c.opts.Transport))
		clientOpts = append(clientOpts, client.Transport(*c.opts.Transport))
	}

	// Parse the server options
	metadata := make(map[string]string)
	for _, d := range ctx.StringSlice("server_metadata") {
		var key, val string
		parts := strings.Split(d, "=")
		key = parts[0]
		if len(parts) > 1 {
			val = strings.Join(parts[1:], "=")
		}
		metadata[key] = val
	}

	if len(metadata) > 0 {
		serverOpts = append(serverOpts, server.Metadata(metadata))
	}

	if len(ctx.String("server_name")) > 0 {
		serverOpts = append(serverOpts, server.Name(ctx.String("server_name")))
	}

	if len(ctx.String("server_version")) > 0 {
		serverOpts = append(serverOpts, server.Version(ctx.String("server_version")))
	}

	if len(ctx.String("server_id")) > 0 {
		serverOpts = append(serverOpts, server.Id(ctx.String("server_id")))
	}

	if len(ctx.String("server_address")) > 0 {
		serverOpts = append(serverOpts, server.Address(ctx.String("server_address")))
	}

	if len(ctx.String("server_advertise")) > 0 {
		serverOpts = append(serverOpts, server.Advertise(ctx.String("server_advertise")))
	}

	// We have some command line opts for the server.
	// Lets set it up
	if len(serverOpts) > 0 {
		(*c.opts.Server).Init(serverOpts...)
	}

	// Use an init option?
	if len(clientOpts) > 0 {
		(*c.opts.Client).Init(clientOpts...)
	}

	return nil
}
コード例 #9
0
ファイル: new.go プロジェクト: Zerak/micro
func run(ctx *cli.Context) {
	namespace := ctx.String("namespace")
	alias := ctx.String("alias")
	fqdn := ctx.String("fqdn")
	atype := ctx.String("type")
	dir := ctx.Args().First()

	if len(dir) == 0 {
		fmt.Println("specify service name")
		return
	}

	if len(namespace) == 0 {
		fmt.Println("namespace not defined")
		return
	}

	if len(atype) == 0 {
		fmt.Println("type not defined")
		return
	}

	// check if the path is absolute, we don't want this
	// we want to a relative path so we can install in GOPATH
	if path.IsAbs(dir) {
		fmt.Println("require relative path as service will be installed in GOPATH")
		return
	}

	goPath := os.Getenv("GOPATH")

	// don't know GOPATH, runaway....
	if len(goPath) == 0 {
		fmt.Println("unknown GOPATH")
		return
	}

	// attempt to split path if not windows
	if runtime.GOOS != "windows" {
		goPath = strings.Split(goPath, ":")[0]
	}

	goDir := filepath.Join(goPath, "src", path.Clean(dir))

	if len(alias) == 0 {
		// set as last part
		alias = filepath.Base(dir)
	}

	if len(fqdn) == 0 {
		fqdn = strings.Join([]string{namespace, atype, alias}, ".")
	}

	var c config

	switch atype {
	case "srv":
		// create srv config
		c = config{
			Alias:     alias,
			Namespace: namespace,
			Type:      atype,
			FQDN:      fqdn,
			Dir:       dir,
			GoDir:     goDir,
			GoPath:    goPath,
			Files: []file{
				{"main.go", tmpl.MainSRV},
				{"handler/example.go", tmpl.HandlerSRV},
				{"subscriber/example.go", tmpl.SubscriberSRV},
				{"proto/example/example.proto", tmpl.ProtoSRV},
				{"Dockerfile", tmpl.DockerSRV},
				{"README.md", tmpl.Readme},
			},
			Comments: []string{
				"\ndownload protobuf for micro:\n",
				"go get github.com/micro/protobuf/{proto,protoc-gen-go}",
				"\ncompile the proto file example.proto:\n",
				fmt.Sprintf("protoc -I%s \\\n\t--go_out=plugins=micro:%s \\\n\t%s\n",
					goPath+"/src", goPath+"/src", goDir+"/proto/example/example.proto"),
			},
		}
	case "api":
		// create api config
		c = config{
			Alias:     alias,
			Namespace: namespace,
			Type:      atype,
			FQDN:      fqdn,
			Dir:       dir,
			GoDir:     goDir,
			GoPath:    goPath,
			Files: []file{
				{"main.go", tmpl.MainAPI},
				{"client/example.go", tmpl.WrapperAPI},
				{"handler/example.go", tmpl.HandlerAPI},
				{"proto/example/example.proto", tmpl.ProtoAPI},
				{"Dockerfile", tmpl.DockerSRV},
				{"README.md", tmpl.Readme},
			},
			Comments: []string{
				"\ndownload protobuf for micro:\n",
				"go get github.com/micro/protobuf/{proto,protoc-gen-go}",
				"\ncompile the proto file example.proto:\n",
				fmt.Sprintf("protoc -I%s \\\n\t--go_out=plugins=micro:%s \\\n\t%s\n",
					goPath+"/src", goPath+"/src", goDir+"/proto/example/example.proto"),
			},
		}
	case "web":
		// create srv config
		c = config{
			Alias:     alias,
			Namespace: namespace,
			Type:      atype,
			FQDN:      fqdn,
			Dir:       dir,
			GoDir:     goDir,
			GoPath:    goPath,
			Files: []file{
				{"main.go", tmpl.MainWEB},
				{"handler/handler.go", tmpl.HandlerWEB},
				{"html/index.html", tmpl.HTMLWEB},
				{"Dockerfile", tmpl.DockerWEB},
				{"README.md", tmpl.Readme},
			},
			Comments: []string{},
		}
	default:
		fmt.Println("Unknown type", atype)
		return
	}

	if err := create(c); err != nil {
		fmt.Println(err)
		return
	}
}
コード例 #10
0
ファイル: web.go プロジェクト: micro/micro
func run(ctx *cli.Context) {
	if len(ctx.String("address")) > 0 {
		Address = ctx.String("address")
	}
	if len(ctx.String("namespace")) > 0 {
		Namespace = ctx.String("namespace")
	}
	if len(ctx.String("cors")) > 0 {
		origins := make(map[string]bool)
		for _, origin := range strings.Split(ctx.String("cors"), ",") {
			origins[origin] = true
		}
		CORS = origins
	}

	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	var h http.Handler
	r := mux.NewRouter()
	s := &srv{r}
	h = s

	if ctx.GlobalBool("enable_stats") {
		statsURL = "/stats"
		st := stats.New()
		s.HandleFunc("/stats", st.StatsHandler)
		h = st.ServeHTTP(s)
		st.Start()
		defer st.Stop()
	}

	s.HandleFunc("/registry", registryHandler)
	s.HandleFunc("/rpc", handler.RPC)
	s.HandleFunc("/cli", cliHandler)
	s.HandleFunc("/query", queryHandler)
	s.HandleFunc("/favicon.ico", faviconHandler)
	s.PathPrefix("/{service:[a-zA-Z0-9]+}").Handler(s.proxy())
	s.HandleFunc("/", indexHandler)

	var opts []server.Option

	if ctx.GlobalBool("enable_tls") {
		config, err := helper.TLSConfig(ctx)
		if err != nil {
			fmt.Println(err.Error())
			return
		}

		opts = append(opts, server.EnableTLS(true))
		opts = append(opts, server.TLSConfig(config))
	}

	// reverse wrap handler
	plugins := append(Plugins(), plugin.Plugins()...)
	for i := len(plugins); i > 0; i-- {
		h = plugins[i-1].Handler()(h)
	}

	srv := server.NewServer(Address)
	srv.Init(opts...)
	srv.Handle("/", h)

	// Initialise Server
	service := micro.NewService(
		micro.Name("go.micro.web"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if err := srv.Start(); err != nil {
		log.Fatal(err)
	}

	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	if err := srv.Stop(); err != nil {
		log.Fatal(err)
	}
}
コード例 #11
0
ファイル: ip_whitelist.go プロジェクト: micro/go-plugins
func (w *whitelist) Init(ctx *cli.Context) error {
	if whitelist := ctx.String("ip_whitelist"); len(whitelist) > 0 {
		w.load(strings.Split(whitelist, ",")...)
	}
	return nil
}
コード例 #12
0
ファイル: cmd.go プロジェクト: ZhuJingfa/go-micro
func (c *cmd) Before(ctx *cli.Context) error {
	// If flags are set then use them otherwise do nothing
	var serverOpts []server.Option
	var clientOpts []client.Option

	// Set the broker
	if name := ctx.String("broker"); len(name) > 0 || len(ctx.String("broker_address")) > 0 {
		if len(name) == 0 {
			name = defaultBroker
		}

		if b, ok := c.opts.Brokers[name]; ok {
			n := b(broker.Addrs(strings.Split(ctx.String("broker_address"), ",")...))
			*c.opts.Broker = n
		} else {
			return fmt.Errorf("Broker %s not found", name)
		}

		serverOpts = append(serverOpts, server.Broker(*c.opts.Broker))
		clientOpts = append(clientOpts, client.Broker(*c.opts.Broker))

	}

	// Set the registry
	if name := ctx.String("registry"); len(name) > 0 || len(ctx.String("registry_address")) > 0 {
		if len(name) == 0 {
			name = defaultRegistry
		}

		if r, ok := c.opts.Registries[name]; ok {
			n := r(registry.Addrs(strings.Split(ctx.String("registry_address"), ",")...))
			*c.opts.Registry = n
		} else {
			return fmt.Errorf("Registry %s not found", name)
		}

		serverOpts = append(serverOpts, server.Registry(*c.opts.Registry))
		clientOpts = append(clientOpts, client.Registry(*c.opts.Registry))

		(*c.opts.Selector).Init(selector.Registry(*c.opts.Registry))
		clientOpts = append(clientOpts, client.Selector(*c.opts.Selector))

		(*c.opts.Broker).Init(broker.Registry(*c.opts.Registry))
	}

	// Set the selector
	if name := ctx.String("selector"); len(name) > 0 {
		if s, ok := c.opts.Selectors[name]; ok {
			n := s(selector.Registry(*c.opts.Registry))
			*c.opts.Selector = n
		} else {
			return fmt.Errorf("Selector %s not found", name)
		}

		// No server option here. Should there be?
		clientOpts = append(clientOpts, client.Selector(*c.opts.Selector))
	}

	// Set the transport
	if name := ctx.String("transport"); len(name) > 0 || len(ctx.String("transport_address")) > 0 {
		if len(name) == 0 {
			name = defaultTransport
		}

		if t, ok := c.opts.Transports[name]; ok {
			n := t(transport.Addrs(strings.Split(ctx.String("transport_address"), ",")...))
			*c.opts.Transport = n
		} else {
			return fmt.Errorf("Transport %s not found", name)
		}

		serverOpts = append(serverOpts, server.Transport(*c.opts.Transport))
		clientOpts = append(clientOpts, client.Transport(*c.opts.Transport))
	}

	// Parse the server options
	metadata := make(map[string]string)
	for _, d := range ctx.StringSlice("server_metadata") {
		var key, val string
		parts := strings.Split(d, "=")
		key = parts[0]
		if len(parts) > 1 {
			val = strings.Join(parts[1:], "=")
		}
		metadata[key] = val
	}

	if len(metadata) > 0 {
		serverOpts = append(serverOpts, server.Metadata(metadata))
	}

	if len(ctx.String("server_name")) > 0 {
		serverOpts = append(serverOpts, server.Name(ctx.String("server_name")))
	}

	if len(ctx.String("server_version")) > 0 {
		serverOpts = append(serverOpts, server.Version(ctx.String("server_version")))
	}

	if len(ctx.String("server_id")) > 0 {
		serverOpts = append(serverOpts, server.Id(ctx.String("server_id")))
	}

	if len(ctx.String("server_address")) > 0 {
		serverOpts = append(serverOpts, server.Address(ctx.String("server_address")))
	}

	if len(ctx.String("server_advertise")) > 0 {
		serverOpts = append(serverOpts, server.Advertise(ctx.String("server_advertise")))
	}

	// client opts
	if r := ctx.Int("client_retries"); r > 0 {
		clientOpts = append(clientOpts, client.Retries(r))
	}

	if t := ctx.String("client_request_timeout"); len(t) > 0 {
		d, err := time.ParseDuration(t)
		if err != nil {
			return fmt.Errorf("failed to parse client_request_timeout: %v", t)
		}
		clientOpts = append(clientOpts, client.RequestTimeout(d))
	}

	if r := ctx.Int("client_pool_size"); r > 0 {
		clientOpts = append(clientOpts, client.PoolSize(r))
	}

	if t := ctx.String("client_pool_ttl"); len(t) > 0 {
		d, err := time.ParseDuration(t)
		if err != nil {
			return fmt.Errorf("failed to parse client_pool_ttl: %v", t)
		}
		clientOpts = append(clientOpts, client.PoolTTL(d))
	}

	// We have some command line opts for the server.
	// Lets set it up
	if len(serverOpts) > 0 {
		(*c.opts.Server).Init(serverOpts...)
	}

	// Use an init option?
	if len(clientOpts) > 0 {
		(*c.opts.Client).Init(clientOpts...)
	}

	return nil
}
コード例 #13
0
ファイル: car.go プロジェクト: micro/micro
func run(ctx *cli.Context, car *sidecar) {
	if len(ctx.String("address")) > 0 {
		Address = ctx.String("address")
	}
	if len(ctx.String("cors")) > 0 {
		origins := make(map[string]bool)
		for _, origin := range strings.Split(ctx.String("cors"), ",") {
			origins[origin] = true
		}
		CORS = origins
	}
	if len(ctx.String("namespace")) > 0 {
		Namespace = ctx.String("namespace")
	}

	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	var opts []server.Option

	if ctx.GlobalBool("enable_tls") {
		config, err := helper.TLSConfig(ctx)
		if err != nil {
			fmt.Println(err.Error())
			return
		}

		opts = append(opts, server.EnableTLS(true))
		opts = append(opts, server.TLSConfig(config))
	}

	r := mux.NewRouter()
	s := &srv{r}

	// new server
	srv := server.NewServer(Address)
	srv.Init(opts...)

	// register handlers
	if car != nil {
		log.Printf("Registering Health handler at %s", HealthPath)
		r.Handle(HealthPath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if c, err := car.hc(); err != nil {
				http.Error(w, err.Error(), c)
				return
			}
		}))
	}

	log.Printf("Registering Registry handler at %s", RegistryPath)
	r.Handle(RegistryPath, http.HandlerFunc(handler.Registry))

	log.Printf("Registering RPC handler at %s", RPCPath)
	r.Handle(RPCPath, http.HandlerFunc(handler.RPC))

	log.Printf("Registering Broker handler at %s", BrokerPath)
	r.Handle(BrokerPath, http.HandlerFunc(handler.Broker))

	log.Printf("Registering Root Handler at %s", RootPath)
	r.PathPrefix(RootPath).Handler(handler.RPCX(Namespace))

	var h http.Handler = s

	if ctx.GlobalBool("enable_stats") {
		st := stats.New()
		r.Handle("/stats", http.HandlerFunc(st.StatsHandler))
		h = st.ServeHTTP(r)
		st.Start()
		defer st.Stop()
	}

	// reverse wrap handler
	plugins := append(Plugins(), plugin.Plugins()...)
	for i := len(plugins); i > 0; i-- {
		h = plugins[i-1].Handler()(h)
	}

	srv.Handle("/", h)

	// Initialise Server
	service := micro.NewService(
		micro.Name("go.micro.sidecar"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if err := srv.Start(); err != nil {
		log.Fatal(err)
	}

	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	if err := srv.Stop(); err != nil {
		log.Fatal(err)
	}
}
コード例 #14
0
ファイル: api.go プロジェクト: micro/micro
func run(ctx *cli.Context) {
	if len(ctx.String("address")) > 0 {
		Address = ctx.String("address")
	}
	if len(ctx.String("handler")) > 0 {
		Handler = ctx.String("handler")
	}
	if len(ctx.String("namespace")) > 0 {
		Namespace = ctx.String("namespace")
	}
	if len(ctx.String("cors")) > 0 {
		origins := make(map[string]bool)
		for _, origin := range strings.Split(ctx.String("cors"), ",") {
			origins[origin] = true
		}
		CORS = origins
	}

	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	// Init API
	var opts []server.Option

	if ctx.GlobalBool("enable_tls") {
		config, err := helper.TLSConfig(ctx)
		if err != nil {
			fmt.Println(err.Error())
			return
		}

		opts = append(opts, server.EnableTLS(true))
		opts = append(opts, server.TLSConfig(config))
	}

	// create the router
	r := mux.NewRouter()
	s := &srv{r}
	var h http.Handler = s

	if ctx.GlobalBool("enable_stats") {
		st := stats.New()
		r.HandleFunc("/stats", st.StatsHandler)
		h = st.ServeHTTP(s)
		st.Start()
		defer st.Stop()
	}

	log.Printf("Registering RPC Handler at %s", RPCPath)
	r.HandleFunc(RPCPath, handler.RPC)

	switch Handler {
	case "rpc":
		log.Printf("Registering API RPC Handler at %s", APIPath)
		r.PathPrefix(APIPath).Handler(handler.RPCX(Namespace))
	case "proxy":
		log.Printf("Registering API Proxy Handler at %s", ProxyPath)
		r.PathPrefix(ProxyPath).Handler(handler.Proxy(Namespace, false))
	default:
		log.Printf("Registering API Default Handler at %s", APIPath)
		r.PathPrefix(APIPath).Handler(handler.API(Namespace))
	}

	// reverse wrap handler
	plugins := append(Plugins(), plugin.Plugins()...)
	for i := len(plugins); i > 0; i-- {
		h = plugins[i-1].Handler()(h)
	}

	// create the server
	api := server.NewServer(Address)
	api.Init(opts...)
	api.Handle("/", h)

	// Initialise Server
	service := micro.NewService(
		micro.Name("go.micro.api"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	// Start API
	if err := api.Start(); err != nil {
		log.Fatal(err)
	}

	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	// Stop API
	if err := api.Stop(); err != nil {
		log.Fatal(err)
	}
}