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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/micro/cli/v2"
     8  	proto "github.com/micro/go-micro/examples/helloworld/proto"
     9  	"github.com/micro/go-micro/examples/mocking/mock"
    10  	"github.com/micro/go-micro/v2"
    11  )
    12  
    13  func main() {
    14  	var c proto.GreeterService
    15  
    16  	service := micro.NewService(
    17  		micro.Flags(&cli.StringFlag{
    18  			Name:  "environment",
    19  			Value: "testing",
    20  		}),
    21  	)
    22  
    23  	service.Init(
    24  		micro.Action(func(ctx *cli.Context) error {
    25  			env := ctx.String("environment")
    26  			// use the mock when in testing environment
    27  			if env == "testing" {
    28  				c = mock.NewGreeterService()
    29  			} else {
    30  				c = proto.NewGreeterService("helloworld", service.Client())
    31  			}
    32  			return nil
    33  		}),
    34  	)
    35  
    36  	// call hello service
    37  	rsp, err := c.Hello(context.TODO(), &proto.Request{
    38  		Name: "John",
    39  	})
    40  	if err != nil {
    41  		fmt.Println(err)
    42  		return
    43  	}
    44  	fmt.Println(rsp.Greeting)
    45  }