Writing a Go Service

This is a guide to getting started with go-micro.

If you prefer a higher level overview of the toolkit first, checkout the introductory blog post https://micro.mu/blog/2016/03/20/micro.html.

Writing a Service

The top level Service interface is the main component for building a service. It wraps all the underlying packages of Go Micro into a single convenient interface.

  1. type Service interface {
  2. Init(...Option)
  3. Options() Options
  4. Client() client.Client
  5. Server() server.Server
  6. Run() error
  7. String() string
  8. }

1. Initialisation

A service is created like so using micro.NewService.

  1. import "github.com/micro/go-micro/v2"
  2. service := micro.NewService()

Options can be passed in during creation.

  1. service := micro.NewService(
  2. micro.Name("greeter"),
  3. micro.Version("latest"),
  4. )

All the available options can be found here.

Go Micro also provides a way to set command line flags using micro.Flags.

  1. import (
  2. "github.com/micro/cli"
  3. "github.com/micro/go-micro/v2"
  4. )
  5. service := micro.NewService(
  6. micro.Flags(
  7. cli.StringFlag{
  8. Name: "environment",
  9. Usage: "The environment",
  10. },
  11. )
  12. )

To parse flags use service.Init. Additionally access flags use the micro.Action option.

  1. service.Init(
  2. micro.Action(func(c *cli.Context) {
  3. env := c.StringFlag("environment")
  4. if len(env) > 0 {
  5. fmt.Println("Environment set to", env)
  6. }
  7. }),
  8. )

Go Micro provides predefined flags which are set and parsed if service.Init is called. See all the flags here.

2. Defining the API

We use protobuf files to define the service API interface. This is a very convenient way to strictly define the API and provide concrete types for both the server and a client.

Here’s an example definition.

greeter.proto

  1. syntax = "proto3";
  2. service Greeter {
  3. rpc Hello(HelloRequest) returns (HelloResponse) {}
  4. }
  5. message HelloRequest {
  6. string name = 1;
  7. }
  8. message HelloResponse {
  9. string greeting = 2;
  10. }

Here we’re defining a service handler called Greeter with the method Hello which takes the parameter HelloRequest type and returns HelloResponse.

3. Generate the API interface

You’ll need the following to generate protobuf code

We use protoc, protoc-gen-go and protoc-gen-micro to generate the concrete go implementation for this definition.

  1. go get github.com/golang/protobuf/{proto,protoc-gen-go}
  1. go get github.com/micro/protoc-gen-micro
  1. protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. greeter.proto

The types generated can now be imported and used within a handler for a server or the client when making a request.

Here’s part of the generated code.

  1. type HelloRequest struct {
  2. Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
  3. }
  4. type HelloResponse struct {
  5. Greeting string `protobuf:"bytes,2,opt,name=greeting" json:"greeting,omitempty"`
  6. }
  7. // Client API for Greeter service
  8. type GreeterClient interface {
  9. Hello(ctx context.Context, in *HelloRequest, opts ...client.CallOption) (*HelloResponse, error)
  10. }
  11. type greeterClient struct {
  12. c client.Client
  13. serviceName string
  14. }
  15. func NewGreeterClient(serviceName string, c client.Client) GreeterClient {
  16. if c == nil {
  17. c = client.NewClient()
  18. }
  19. if len(serviceName) == 0 {
  20. serviceName = "greeter"
  21. }
  22. return &greeterClient{
  23. c: c,
  24. serviceName: serviceName,
  25. }
  26. }
  27. func (c *greeterClient) Hello(ctx context.Context, in *HelloRequest, opts ...client.CallOption) (*HelloResponse, error) {
  28. req := c.c.NewRequest(c.serviceName, "Greeter.Hello", in)
  29. out := new(HelloResponse)
  30. err := c.c.Call(ctx, req, out, opts...)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return out, nil
  35. }
  36. // Server API for Greeter service
  37. type GreeterHandler interface {
  38. Hello(context.Context, *HelloRequest, *HelloResponse) error
  39. }
  40. func RegisterGreeterHandler(s server.Server, hdlr GreeterHandler) {
  41. s.Handle(s.NewHandler(&Greeter{hdlr}))
  42. }

4. Implement the handler

The server requires handlers to be registered to serve requests. A handler is an public type with public methods which conform to the signature func(ctx context.Context, req interface{}, rsp interface{}) error.

As you can see above, a handler signature for the Greeter interface looks like so.

  1. type GreeterHandler interface {
  2. Hello(context.Context, *HelloRequest, *HelloResponse) error
  3. }

Here’s an implementation of the Greeter handler.

  1. import proto "github.com/micro/examples/service/proto"
  2. type Greeter struct{}
  3. func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
  4. rsp.Greeting = "Hello " + req.Name
  5. return nil
  6. }

The handler is registered with your service much like a http.Handler.

  1. service := micro.NewService(
  2. micro.Name("greeter"),
  3. )
  4. proto.RegisterGreeterHandler(service.Server(), new(Greeter))

You can also create a bidirectional streaming handler but we’ll leave that for another day.

5. Running the service

The service can be run by calling server.Run. This causes the service to bind to the address in the config (which defaults to the first RFC1918 interface found and a random port) and listen for requests.

This will additionally Register the service with the registry on start and Deregister when issued a kill signal.

  1. if err := service.Run(); err != nil {
  2. log.Fatal(err)
  3. }

6. The complete service

greeter.go

  1. package main
  2. import (
  3. "log"
  4. "github.com/micro/go-micro/v2"
  5. proto "github.com/micro/examples/service/proto"
  6. "golang.org/x/net/context"
  7. )
  8. type Greeter struct{}
  9. func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
  10. rsp.Greeting = "Hello " + req.Name
  11. return nil
  12. }
  13. func main() {
  14. service := micro.NewService(
  15. micro.Name("greeter"),
  16. micro.Version("latest"),
  17. )
  18. service.Init()
  19. proto.RegisterGreeterHandler(service.Server(), new(Greeter))
  20. if err := service.Run(); err != nil {
  21. log.Fatal(err)
  22. }
  23. }

Note. The service discovery mechanism will need to be running so the service can register to be discovered by clients and other services. A quick getting started for that is here.

Writing a Client

The client package is used to query services. When you create a Service, a Client is included which matches the initialised packages used by the server.

Querying the above service is as simple as the following.

  1. // create the greeter client using the service name and client
  2. greeter := proto.NewGreeterService("greeter", service.Client())
  3. // request the Hello method on the Greeter handler
  4. rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{
  5. Name: "John",
  6. })
  7. if err != nil {
  8. fmt.Println(err)
  9. return
  10. }
  11. fmt.Println(rsp.Greeting)

proto.NewGreeterClient takes the service name and the client used for making requests.

The full example is can be found at go-micro/examples/service.