Getting Started

This is a getting started guide for Micro which teaches you how to go from install to helloworld and beyond.

Dependencies

You will need protoc-gen-micro for code generation

  1. # Download latest proto releaes
  2. # https://github.com/protocolbuffers/protobuf/releases
  3. go get github.com/golang/protobuf/protoc-gen-go
  4. go get github.com/micro/micro/v3/cmd/protoc-gen-micro

Install

Go Get

Using Go:

  1. go install github.com/micro/micro/v3@latest

Release Binary

Or by downloading the binary

  1. # MacOS
  2. curl -fsSL https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh | /bin/bash
  3. # Linux
  4. wget -q https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh -O - | /bin/bash
  5. # Windows
  6. powershell -Command "iwr -useb https://raw.githubusercontent.com/micro/micro/master/scripts/install.ps1 | iex"

Docker Image

  1. docker pull micro/micro

Helm Chart

  1. helm repo add micro https://micro.github.io/helm
  2. helm install micro micro/micro

Running a service

Before diving into writing a service, let’s run an existing one, because it’s just a few commands away!

First, we have to start the micro server. The command to do that is:

  1. micro server

Before interacting with the micro server, we need to log in with the id ‘admin’ and password ‘micro’:

  1. $ micro login
  2. Enter username: admin
  3. Enter password:
  4. Successfully logged in.

If all goes well you’ll see log output from the server listing the services as it starts them. Just to verify that everything is in order, let’s see what services are running:

  1. $ micro services
  2. api
  3. auth
  4. broker
  5. config
  6. events
  7. network
  8. proxy
  9. registry
  10. runtime
  11. server
  12. store

All those services are ones started by our micro server. This is pretty cool, but still it’s not something we launched! Let’s start a service for which existence we can actually take credit for. If we go to github.com/micro/services, we see a bunch of services written by micro authors. One of them is the helloworld. Try our luck, shall we?

The command to run services is micro run.

Simply issue the following command

  1. $ micro run github.com/micro/services/helloworld

Now check the status of the running service

  1. $ micro status
  2. NAME VERSION SOURCE STATUS BUILD UPDATED METADATA
  3. helloworld latest github.com/micro/services/helloworld running n/a 4s ago owner=admin, group=micro

We can also have a look at logs of the service to verify it’s running.

  1. $ micro logs helloworld
  2. 2020-10-06 17:52:21 file=service/service.go:195 level=info Starting [service] helloworld
  3. 2020-10-06 17:52:21 file=grpc/grpc.go:902 level=info Server [grpc] Listening on [::]:33975
  4. 2020-10-06 17:52:21 file=grpc/grpc.go:732 level=info Registry [service] Registering node: helloworld-67627b23-3336-4b92-a032-09d8d13ecf95

So since our service is running happily, let’s try to call it! That’s what services are for.

Calling a service

We have a couple of options to call a service running on our micro server.

With the CLI

Micro auto-generates CLI commands for your service in the form: micro [service] [method], with the default method being “Call”. Arguments can be passed as flags, hence we can call our service using:

  1. $ micro helloworld --name=Jane
  2. {
  3. "msg": "Hello Jane"
  4. }

That worked! If we wonder what endpoints a service has we can run the following command:

  1. $ micro helloworld --help
  2. NAME:
  3. micro helloworld
  4. VERSION:
  5. latest
  6. USAGE:
  7. micro helloworld [command]
  8. COMMANDS:
  9. call

To see the flags for subcommands of helloworld:

  1. $ micro helloworld call --help
  2. NAME:
  3. micro helloworld call
  4. USAGE:
  5. micro helloworld call [flags]
  6. FLAGS:
  7. --name string

With the API

Micro exposes a http API on port 8080 so you can just curl your service like so.

  1. curl "http://localhost:8080/helloworld?name=John"

With the Framework

Let’s write a small client we can use to call the helloworld service. Normally you’ll make a service call inside another service so this is just a sample of a function you may write. We’ll learn how to write a full fledged service soon.

Let’s take the following file:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/micro/micro/v3/service"
  7. proto "github.com/micro/services/helloworld/proto"
  8. )
  9. func main() {
  10. // create and initialise a new service
  11. srv := service.New()
  12. // create the proto client for helloworld
  13. client := proto.NewHelloworldService("helloworld", srv.Client())
  14. // call an endpoint on the service
  15. rsp, err := client.Call(context.Background(), &proto.CallRequest{
  16. Name: "John",
  17. })
  18. if err != nil {
  19. fmt.Println("Error calling helloworld: ", err)
  20. return
  21. }
  22. // print the response
  23. fmt.Println("Response: ", rsp.Message)
  24. // let's delay the process for exiting for reasons you'll see below
  25. time.Sleep(time.Second * 5)
  26. }

Save the example locally. For ease of following this guide, name the folder example. After doing a cd example && go mod init example, we are ready to run this service with micro run:

  1. micro run .

micro runs, when successful, do not print any output. A useful command to see what is running, is micro status. At this point we should have two services running:

  1. $ micro status
  2. NAME VERSION SOURCE STATUS BUILD UPDATED METADATA
  3. example latest example.tar.gz running n/a 2s ago owner=admin, group=micro
  4. helloworld latest github.com/micro/services/helloworld running n/a 5m59s ago owner=admin, group=micro

Now, since our example service client is also running, we should be able to see it’s logs:

  1. $ micro logs example
  2. # some go build output here
  3. Response: Hello John

Great! That response is coming straight from the helloworld service we started earlier!

Multi-Language Clients

Soon we’ll be releasing multi language grpc generated clients to query services and use micro also.

Creating a service

To create a new service, use the micro new command. It should output something reasonably similar to the following:

  1. $ micro new helloworld
  2. Creating service helloworld
  3. .
  4. ├── main.go
  5. ├── generate.go
  6. ├── handler
  7. └── helloworld.go
  8. ├── proto
  9. └── helloworld.proto
  10. ├── Dockerfile
  11. ├── Makefile
  12. ├── README.md
  13. ├── .gitignore
  14. └── go.mod
  15. download protoc zip packages (protoc-$VERSION-$PLATFORM.zip) and install:
  16. visit https://github.com/protocolbuffers/protobuf/releases
  17. download protobuf for micro:
  18. go get -u github.com/golang/protobuf/proto
  19. go get -u github.com/golang/protobuf/protoc-gen-go
  20. go get github.com/micro/micro/v3/cmd/protoc-gen-micro
  21. compile the proto file helloworld.proto:
  22. cd helloworld
  23. make proto

As can be seen from the output above, before building the first service, the following tools must be installed:

They are all needed to translate proto files to actual Go code. Protos exist to provide a language agnostic way to describe service endpoints, their input and output types, and to have an efficient serialization format at hand.

So once all tools are installed, being inside the service root, we can issue the following command to generate the Go code from the protos:

  1. make proto

The generated code must be committed to source control, to enable other services to import the proto when making service calls (see previous section Calling a service.

At this point, we know how to write a service, run it, and call other services too. We have everything at our fingertips, but there are still some missing pieces to write applications. One of such pieces is the store interface, which helps with persistent data storage even without a database.

Storage

Amongst many other useful built-in services Micro includes a persistent storage service for storing data.

With the CLI

First, let’s go over the more basic store CLI commands.

To save a value, we use the write command:

  1. $ micro store write key1 val1

The UNIX style no output meant it was happily saved. What about reading it?

  1. $ micro store read key1
  2. val1

Or to display it in a fancier way, we can use the --verbose or -v flags.

  1. $ micro store read -v key1
  2. KEY VALUE EXPIRY
  3. key1 val1 None

This view is especially useful when we use the --prefix or -p flag, which lets us search for entries which key have certain prefixes.

To demonstrate that first let’s save an other value:

  1. $ micro store write key2 val2

After this, we can list both key1 and key2 keys as they both share common prefixes:

  1. $ micro store read --prefix --verbose key
  2. KEY VALUE EXPIRY
  3. key1 val1 None
  4. key2 val2 None

There is more to the store, but this knowledge already enables us to be dangerous!

With the Framework

Accessing the same data we have just manipulated from our Go Micro services could not be easier. First let’s create an entry that our service can read. This time we will specify the table for the micro store write command too, as each service has its own table in the store:

  1. micro store write --table=example mykey "Hi there"

Let’s modify the example service we wrote previously so instead of calling a service, it reads the above value from a store.

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/micro/micro/v3/service"
  6. "github.com/micro/micro/v3/service/store"
  7. )
  8. func main() {
  9. srv := service.New(service.Name("example"))
  10. srv.Init()
  11. records, err := store.Read("mykey", func(r *store.ReadOptions) {
  12. r.Table = "example"
  13. })
  14. if err != nil {
  15. fmt.Println("Error reading from store: ", err)
  16. }
  17. if len(records) == 0 {
  18. fmt.Println("No records")
  19. }
  20. for _, record := range records {
  21. fmt.Printf("key: %v, value: %v\n", record.Key, string(record.Value))
  22. }
  23. time.Sleep(1 * time.Hour)
  24. }

Updating a service

Now since the example service is running (can be easily verified by micro status), we should not use micro run, but rather micro update to deploy it.

We can simply issue the update command (remember to switch back to the root directory of the example service first):

  1. micro update .

And verify both with micro status:

  1. $ micro status example
  2. NAME VERSION SOURCE STATUS BUILD UPDATED METADATA
  3. example latest n/a running n/a 7s ago owner=admin, group=micro

that it was updated.

If things for some reason go haywire, we can try the time tested “turning it off and on again” solution and do:

  1. micro kill example
  2. micro run .

to start with a clean slate.

So once we did update the example service, we should see the following in the logs:

  1. $ micro logs example
  2. key: mykey, value: Hi there

Config

Configuration and secrets is an essential part of any production system - let’s see how the Micro config works.

With the CLI

The most basic example of config usage is the following:

  1. $ micro config set key val
  2. $ micro config get key
  3. val

While this alone is enough for a great many use cases, for purposes of organisation, Micro also support dot notation of keys. Let’s overwrite our keys set previously:

  1. $ micro config del key
  2. $ micro config set key.subkey val
  3. $ micro config get key.subkey
  4. val

This is fairly straightforward, but what happens when we get key?

  1. $ micro config get key
  2. {"subkey":"val"}

As it can be seen, leaf level keys will return only the value, while node level keys return the whole subtree as a JSON document:

  1. $ micro config set key.othersubkey val2
  2. $ micro config get key
  3. {"othersubkey":"val2","subkey":"val"}

With the Framework

Micro configs work very similarly when being called from Go code too:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/micro/micro/v3/service"
  5. "github.com/micro/micro/v3/service/config"
  6. )
  7. func main() {
  8. // setup the service
  9. srv := service.New(service.Name("example"))
  10. srv.Init()
  11. // read config value
  12. val, _ := config.Get("key.subkey")
  13. fmt.Println("Value of key.subkey: ", val.String(""))
  14. }

Assuming the folder name for this service is still example (to update the existing service, see updating a service):

  1. $ micro logs example
  2. Value of key.subkey: val

Further Resources

This is just a brief getting started guide for quickly getting up and running with Micro. Come back from time to time to learn more as this guide gets continually upgraded. If you’re interested in learning more Micro magic, have a look at the following sources:

This site is open source. Improve this page.