forked from asbubam/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (69 loc) · 1.77 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"os"
"context"
"github.com/micro/cli/v2"
proto "github.com/micro/examples/service/proto"
"github.com/micro/go-micro/v2"
)
/*
Example usage of top level service initialisation
*/
type Greeter struct{}
func (g *Greeter) Hello(ctx context.Context, req *proto.Request, rsp *proto.Response) error {
rsp.Greeting = "Hello " + req.Name
return nil
}
// Setup and the client
func runClient(service micro.Service) {
// Create new greeter client
greeter := proto.NewGreeterService("greeter", service.Client())
// Call the greeter
rsp, err := greeter.Hello(context.TODO(), &proto.Request{Name: "John"})
if err != nil {
fmt.Println(err)
return
}
// 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
// Add runtime flags
// We could do this below too
micro.Flags(&cli.BoolFlag{
Name: "run_client",
Usage: "Launch the client",
}),
)
// 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.
service.Init(
// Add runtime action
// We could actually do this above
micro.Action(func(c *cli.Context) error {
if c.Bool("run_client") {
runClient(service)
os.Exit(0)
}
return nil
}),
)
// 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)
}
}