github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/roundrobin/api.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "log" 6 "strings" 7 8 hello "github.com/micro/go-micro/examples/greeter/srv/proto/hello" 9 "github.com/micro/go-micro/v2" 10 "github.com/micro/go-micro/v2/errors" 11 roundrobin "github.com/micro/go-plugins/wrapper/select/roundrobin/v2" 12 api "github.com/micro/micro/v2/api/proto" 13 14 "context" 15 ) 16 17 type Say struct { 18 Client hello.SayService 19 } 20 21 func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error { 22 log.Print("Received Say.Hello API request") 23 24 name, ok := req.Get["name"] 25 if !ok || len(name.Values) == 0 { 26 return errors.BadRequest("go.micro.api.greeter", "Name cannot be blank") 27 } 28 29 response, err := s.Client.Hello(ctx, &hello.Request{ 30 Name: strings.Join(name.Values, " "), 31 }) 32 if err != nil { 33 return err 34 } 35 36 rsp.StatusCode = 200 37 b, _ := json.Marshal(map[string]string{ 38 "message": response.Msg, 39 }) 40 rsp.Body = string(b) 41 42 return nil 43 } 44 45 func main() { 46 wrapper := roundrobin.NewClientWrapper() 47 48 service := micro.NewService( 49 micro.Name("go.micro.api.greeter"), 50 micro.WrapClient(wrapper), 51 ) 52 53 // parse command line flags 54 service.Init() 55 56 service.Server().Handle( 57 service.Server().NewHandler( 58 &Say{Client: hello.NewSayService("go.micro.srv.greeter", service.Client())}, 59 ), 60 ) 61 62 if err := service.Run(); err != nil { 63 log.Fatal(err) 64 } 65 }