import ( "github.com/micro/go-micro/v2" "context" "greeter-service/proto"// replace greeter-service if you didn't name greeter-service when go mod init "log" )
// GreeterService ... type GreeterService struct {}
// Greet ... Implement interface left in proto/greeter.pb.micro.go server part func(g *GreeterService) Greet(ctx context.Context, req *greeter.Request, res *greeter.Response) error { log.Println("Greeter service handle Greet", req.Name) res.Greeting = "Hello, " + req.Name returnnil }
funcmain() { service := micro.NewService( micro.Name("micro.service.greeter"), // The service name to register in the registry )
service.Init()
// The 'RegisterGreeterHandler' is implement in the proto/greeter.pb.micro.go file greeter.RegisterGreeterHandler(service.Server(), &GreeterService{}) if err := service.Run(); err != nil { log.Print(err.Error()) return } }
// Init ... In the main function, you should call Init() first, // so the 'client' defined above can be initialized. funcInit() { service := micro.NewService( micro.Name("micro.client.greeter"), )
service.Init()
// NewGreeterService is defined at proto/greeter.pb.micro.go file, // "micro.service.greeter" should match the name you defined in the server part. client = greeter.NewGreeterService("micro.service.greeter", service.Client()) }
// Greet ... funcGreet(ctx *gin.Context) { name := ctx.Query("name") // ctx.Query will return the GET request query string log.Println("Client handle Greet, name =", name)
// Client request the RPC server for response res, err := client.Greet(context.TODO(), &greeter.Request{Name: name}) if err != nil { log.Print(err.Error()) // return with 400 error code and error message ctx.JSON(400, gin.H{"message": "server error"}) return }
// return 200 success code and the response from server ctx.JSON(200, gin.H{"message": res.Greeting}) }
// NewRouter ... funcNewRouter() *gin.Engine { route := gin.Default() // When GET /greeter, handle the request with the Greet function we create above route.GET("/greeter", client.Greet) return route }
funcmain() { // Remember to call the Init() function to initialize the go-micro client service client.Init() // Start Gin Router at port 3000 r := router.NewRouter() if err := r.Run("0.0.0.0:3000"); err != nil { log.Print(err.Error()) } }
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in"debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /greeter --> greeter-api/client.Greet (3 handlers) [GIN-debug] Listening and serving HTTP on 0.0.0.0:3000