github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/service/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"context"
     8  	"github.com/micro/cli/v2"
     9  	proto "github.com/micro/go-micro/examples/service/proto"
    10  	"github.com/micro/go-micro/v2"
    11  )
    12  
    13  /*
    14  
    15  Example usage of top level service initialisation
    16  
    17  */
    18  
    19  type Greeter struct{}
    20  
    21  func (g *Greeter) Hello(ctx context.Context, req *proto.Request, rsp *proto.Response) error {
    22  	rsp.Greeting = "Hello " + req.Name
    23  	return nil
    24  }
    25  
    26  // Setup and the client
    27  func runClient(service micro.Service) {
    28  	// Create new greeter client
    29  	greeter := proto.NewGreeterService("greeter", service.Client())
    30  
    31  	// Call the greeter
    32  	rsp, err := greeter.Hello(context.TODO(), &proto.Request{Name: "John"})
    33  	if err != nil {
    34  		fmt.Println(err)
    35  		return
    36  	}
    37  
    38  	// Print response
    39  	fmt.Println(rsp.Greeting)
    40  }
    41  
    42  func main() {
    43  	// Create a new service. Optionally include some options here.
    44  	service := micro.NewService(
    45  		micro.Name("greeter"),
    46  		micro.Version("latest"),
    47  		micro.Metadata(map[string]string{
    48  			"type": "helloworld",
    49  		}),
    50  
    51  		// Setup some flags. Specify --run_client to run the client
    52  
    53  		// Add runtime flags
    54  		// We could do this below too
    55  		micro.Flags(&cli.BoolFlag{
    56  			Name:  "run_client",
    57  			Usage: "Launch the client",
    58  		}),
    59  	)
    60  
    61  	// Init will parse the command line flags. Any flags set will
    62  	// override the above settings. Options defined here will
    63  	// override anything set on the command line.
    64  	service.Init(
    65  		// Add runtime action
    66  		// We could actually do this above
    67  		micro.Action(func(c *cli.Context) error {
    68  			if c.Bool("run_client") {
    69  				runClient(service)
    70  				os.Exit(0)
    71  			}
    72  			return nil
    73  		}),
    74  	)
    75  
    76  	// By default we'll run the server unless the flags catch us
    77  
    78  	// Setup the server
    79  
    80  	// Register handler
    81  	proto.RegisterGreeterHandler(service.Server(), new(Greeter))
    82  
    83  	// Run the server
    84  	if err := service.Run(); err != nil {
    85  		fmt.Println(err)
    86  	}
    87  }