87 lines
1.8 KiB
Go
Raw Normal View History

2016-01-01 01:16:21 +00:00
package main
import (
"fmt"
"os"
"github.com/micro/cli"
2016-01-02 23:15:57 +00:00
"github.com/micro/go-micro"
2016-01-01 01:16:21 +00:00
proto "github.com/micro/go-micro/examples/service/proto"
"golang.org/x/net/context"
)
/*
Example usage of top level service initialisation
*/
type Greeter struct{}
func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
rsp.Greeting = "Hello " + req.Name
return nil
}
// Setup and the client
2016-01-02 23:15:57 +00:00
func runClient(service micro.Service) {
2016-01-01 01:16:21 +00:00
// Create new greeter client
greeter := proto.NewGreeterClient("greeter", service.Client())
// Call the greeter
rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{Name: "John"})
if err != nil {
fmt.Println(err)
2016-01-02 23:15:57 +00:00
return
2016-01-01 01:16:21 +00:00
}
// Print response
fmt.Println(rsp.Greeting)
}
func main() {
// Create a new service. Optionally include some options here.
service := micro.NewService(
micro.Name("greeter"),
micro.Version("latest"),
micro.Metadata(map[string]string{
"type": "helloworld",
}),
// Setup some flags. Specify --run_client to run the client
2016-01-02 19:12:17 +00:00
// Add runtime flags
// We could do this below too
micro.Flags(cli.BoolFlag{
Name: "run_client",
2016-01-02 19:12:17 +00:00
Usage: "Launch the client",
}),
)
2016-01-01 01:16:21 +00:00
// Init will parse the command line flags. Any flags set will
// override the above settings. Options defined here will
// override anything set on the command line.
2016-01-02 19:12:17 +00:00
service.Init(
// Add runtime action
// We could actually do this above
micro.Action(func(c *cli.Context) {
if c.Bool("run_client") {
2016-01-02 23:15:57 +00:00
runClient(service)
2016-01-02 19:12:17 +00:00
os.Exit(0)
}
}),
)
2016-01-01 01:16:21 +00:00
// By default we'll run the server unless the flags catch us
// Setup the server
// Register handler
proto.RegisterGreeterHandler(service.Server(), new(Greeter))
// Run the server
if err := service.Run(); err != nil {
fmt.Println(err)
}
}