CURRENTLY BEING UPDATED

用中文阅读.

Sponsor me on Patreon to support more content like this.

In the previous post, we covered some of the basics of go-micro and Docker. We also introduced a second service. In this post, we're going to look at docker-compose, and how we can run our services together locally a little easier. We're going to introduce some different databases, and finally we'll introduce a third service into the mix.

Prerequisites

Install docker-compose: https://docs.docker.com/compose/install/

But first, let's look at databases.

Choosing a database

So far our data isn't actually stored anywhere, it's stored in memory in our services, which is then lost when our containers are restarted. So of course we need a way of persisting, storing and querying our data.

The beauty of microservices, is that you can use different databases per service. Of course you don't have to do this, and many people don't. In fact I rarely do for small teams as it's a bit of a mental leap to maintain several different databases, than just one. But in some cases, one services data, might not fit the database you've used for your other services. So it makes sense to use something else. Microservices makes this trivially easy as your concerns are completely separate.

Choosing the 'correct' database for your services is an entirely different article, this one for example, so we wont go into too much detail on this subect. However, I will say that if you have fairly loose or inconsistent datasets, then a NoSQL document store solution is perfect. They're much more flexible with what you can store and work well with json. We'll be using MongoDB for our NoSQL database. No particular reason other than it performs well, it's widely used and supported and has a great online community.

If your data is more strictly defined and relational by nature, then it can makes sense to use a traditional rdbms, or relational database. But there really aren't any hard rules, generally any will do the job. But be sure to look at your data structure, consider whether your service is doing more reading or more writing, how complex the queries will be, and try to use those as a starting point in choosing your databases. For our relational database, we'll be using Postgres. Again, no particular reason other than it does the job well and I'm familiar with it. You could use MySQL, MariaDB, or something else.

Amazon and Google both have some fantastic on premises solution for both of these database types as well, if you wanted to avoid managing your own databases (generally advisable). Another great option is compose, who will spin up fully managed, scalable instances of various database technologies, using the same cloud provider as your services to avoid connection latency.

Amazon:RDBMS: https://aws.amazon.com/rds/NoSQL: https://aws.amazon.com/dynamodb/

Google:RDBMS: https://cloud.google.com/spanner/NoSQL: https://cloud.google.com/datastore/

Now that we've discussed databases a little, let's do some coding!

docker-compose

In the last part in the series we looked at Docker, which let us run our services in light-weight containers with their own run-times and dependencies. However, it's getting slightly cumbersome to have to run and manage each service with a separate Makefile. So let's take a look at docker-compose. Docker-compose allows you do define a list of docker containers in a yaml file, and specify metadata about their run-time. Docker-compose services map more or less to the same docker commands we're already using. For example:

$ docker run -p 50052:50051 -e MICRO_SERVER_ADDRESS=:50051 -e MICRO_REGISTRY=mdns vessel-service

Becomes:

  1. version: '3.1'
  2. services:
  3. shippy-service-vessel:
  4. build: ./shippy-service-vessel
  5. ports:
  6. - 50052:50051
  7. environment:
  8. MICRO_SERVER_ADDRESS: ":50051"

Easy!

So let's create a docker-compose file in the root of our directory $ touch docker-compose.yml. Now add our services:

  1. # docker-compose.yml
  2. version: '3.1'
  3. services:
  4. shippy-cli-consignment:
  5. build: ./shippy-cli-consignment
  6. shippy-service-consignment:
  7. build: ./shippy-service-consignment
  8. ports:
  9. - 50051:50051
  10. environment:
  11. MICRO_ADDRESS: ":50051"
  12. DB_HOST: "datastore:27017"
  13. shippy-service-vessel:
  14. build: ./shippy-service-vessel
  15. ports:
  16. - 50052:50051
  17. environment:
  18. MICRO_ADDRESS: ":50051"

First we define the version of docker-compose we want to use, then a list of services. There are other root level definitions such as networks and volumes, but we'll just focus on services for now.

Each service is defined by its name, then we include a build path, which is a reference to a location, which should contain a Dockerfile. This tells docker-compose to use this Dockerfile to build its image. You can also use image here to use a pre-built image. Which we will be doing later on. Then you define your port mappings, and finally your environment variables.

To build your docker-compose stack, simply run $ docker-compose build, and to run it, $ docker-compose run. To run your stack in the background, use $ docker-compose up -d. You can also view a list of your currently running containers at any point using $ docker ps. Finally, you can stop all of your current containers by running $ docker stop $(docker ps -qa).

So let's run our stack. You should see lots of output and dockerfile's being built. You may also see an error from our CLI tool, but don't worry about that, it's mostly likely because it's ran prior to our other services. It's simply saying that it can't find them yet.

Let's test it all worked by running our CLI tool. To run it through docker-compose, simply run $ docker-compose run consignment-cli once all of the other containers are running. You should see it run successfully, just as before.

Entities and protobufs

Throughout this series we've spoken of protobufs being the very center of our data model. We've used it to define our services structure and functionality. Because protobuf generates structs with more or less all of the correct data types, we can also re-use these structs as our underlying database models. This is actually pretty mind-blowing. It keeps in-line with the protobuf being the single source of truth.

However this approach does have its down-sides. Sometimes its tricky to marshal the code generated by protobuf into a valid database entity. Sometimes database technologies use custom types which are tricky to translate from the native types generated by protobuf. One problem I spent many many hours thinking about was how I could convert Id string to and from Id bson.ObjectId for Mongodb entities. It turns out that bson.ObjectId, is really just a string anyway, so you can marshal them together. Also, mongodb's id index is stored as _id internally, so you need a way to tie that to your Id string field as you can't really do _Id string. Which means finding a way to define custom tags for your protobuf files. But we'll get to that later.

Also, many people often argue against using your protobuf definitions as your database entity because you're tightly coupling your communication technology to your database code. Which is also a valid point.

Generally it's advised to convert between your protobuf definition code and your database entities. However, you end up with a lot of conversion code for converting two almost identical types, for example:

  1. func (service *Service) (ctx context.Context, req *proto.User, res *proto.Response) error {
  2. entity := &models.User{
  3. Name: req.Name.
  4. Email: req.Email,
  5. Password: req.Password,
  6. }
  7. err := service.repo.Create(entity)
  8. ...
  9. }

Which on the surface doesn't seem all that bad, but when you've got several nested structs, and several types. It can be really tedious, and can involve a lot of iteration to convert between nested structs etc.

This approach is really down to you though, like many things in programming, this doesn't come down to a right or wrong. So take whichever approach feels most appropriate to you. But, my own personal opinion is that converting between two almost identical types, especially given we're treating our protobuf code as the basis of our data, feels like a detraction from the benefits we've attained from using protobufs as your core definition. So I will be using our protobuf code for our database. By the way, I'm not saying I'm right on this, and I'm desperate to hear your opinions on this.

Let's start hooking up our first service, our consignment service. I feel as though we should do some tidying up first. We've lumped everything into our main.go file. I know these are microservices, but that's no excuse to be messy! So let's create two more files in shippy-service-consignment, handler.go, datastore.go, and repository.go. I'm creating these within the root of our service, rather than creating them as new packages and directories. This is perfectly adequate for a small microservice. It's a common temptation for developers to create a structure like this:

  1. main.go
  2. models/
  3. user.go
  4. handlers/
  5. auth.go
  6. user.go
  7. services/
  8. auth.go

This harks back to the MVC days, and isn't really advised in Golang. Certainly not for smaller projects. If you had a bigger project with multiple concerns, you could organise it as followed:

  1. main.go
  2. users/
  3. services/
  4. auth.go
  5. handlers/
  6. auth.go
  7. user.go
  8. users/
  9. user.go
  10. containers/
  11. services/
  12. manage.go
  13. models/
  14. container.go

Here you're grouping your code by domain, rather than arbitrarily grouping your code by what it does.

However, as we're dealing with a microservice, which should only really be dealing with a single concern, we don't need to take either of the above approaches. In fact, Go's ethos is to encourage simplicity. So we'll start simple and house everything in the root of our service, with some clearly defined file names.

As a side note, we'll need to update our Dockerfile's, as we're not importing our new separated code as packages, we will need to tell the go compiler to pull in these new files. So update the build function to look like this:

  1. RUN CGO_ENABLED=0 GOOS=linux go build -o shippy-service-consignment -a -installsuffix cgo main.go repository.go handler.go datastore.go

This will include the new files we'll be creating.

The MongoDB Golang lib is a great example of this simplicity and finally on this, here's a great article on organising Go codebases.

Let's start by removing all of the repository code from our main.go and re-purpose it to use the mongodb library, mgo. Once again, I've tried to comment the code to explain what each part does, so please read the code and comments thoroughly. Especially the part around how mgo handles sessions:

  1. // shippy-service-consignment/repository.go
  2. package main
  3. import (
  4. "context"
  5. pb "github.com/EwanValentine/shippy-service-consignment/proto/consignment"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. )
  8. type repository interface {
  9. Create(consignment *pb.Consignment) error
  10. GetAll() ([]*pb.Consignment, error)
  11. }
  12. // MongoRepository implementation
  13. type MongoRepository struct {
  14. collection *mongo.Collection
  15. }
  16. // Create -
  17. func (repository *MongoRepository) Create(consignment *pb.Consignment) error {
  18. _, err := repository.collection.InsertOne(context.Background(), consignment)
  19. return err
  20. }
  21. // GetAll -
  22. func (repository *MongoRepository) GetAll() ([]*pb.Consignment, error) {
  23. cur, err := repository.collection.Find(context.Background(), nil, nil)
  24. var consignments []*pb.Consignment
  25. for cur.Next(context.Background()) {
  26. var consignment *pb.Consignment
  27. if err := cur.Decode(&consignment); err != nil {
  28. return nil, err
  29. }
  30. consignments = append(consignments, consignment)
  31. }
  32. return consignments, err
  33. }

So there we have our code responsible for interacting with our Mongodb database. We'll need to create the code that creates the master session/connection. Update consignment-service/datastore.go with the following:

  1. // shippy-service-consignment/datastore.go
  2. package main
  3. import (
  4. "context"
  5. "go.mongodb.org/mongo-driver/mongo"
  6. "go.mongodb.org/mongo-driver/mongo/options"
  7. "time"
  8. )
  9. // CreateClient -
  10. func CreateClient(uri string) (*mongo.Client, error) {
  11. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  12. return mongo.Connect(ctx, options.Client().ApplyURI(uri))
  13. }

That's it, pretty straight forward. It takes a host string as an argument, returns a session to our datastore and of course a potential error, so that we can handle that on start-up. Let's modify our main.go file to hook this up to our repository:

  1. // shippy-service-consignment/main.go
  2. package main
  3. import (
  4. "context"
  5. "fmt"
  6. pb "github.com/EwanValentine/shippy-service-consignment/proto/consignment"
  7. vesselProto "github.com/EwanValentine/shippy-service-vessel/proto/vessel"
  8. "github.com/micro/go-micro"
  9. "log"
  10. "os"
  11. )
  12. const (
  13. port = ":50051"
  14. defaultHost = "datastore:27017"
  15. )
  16. func main() {
  17. // Set-up micro instance
  18. srv := micro.NewService(
  19. micro.Name("shippy.service.consignment"),
  20. )
  21. srv.Init()
  22. uri := os.Getenv("DB_HOST")
  23. if uri == "" {
  24. uri = defaultHost
  25. }
  26. client, err := CreateClient(uri)
  27. if err != nil {
  28. log.Panic(err)
  29. }
  30. defer client.Disconnect(context.TODO())
  31. consignmentCollection := client.Database("shippy").Collection("consignments")
  32. repository := &MongoRepository{consignmentCollection}
  33. vesselClient := vesselProto.NewVesselServiceClient("shippy.service.client", srv.Client())
  34. h := &handler{repository, vesselClient}
  35. // Register handlers
  36. pb.RegisterShippingServiceHandler(srv.Server(), h)
  37. // Run the server
  38. if err := srv.Run(); err != nil {
  39. fmt.Println(err)
  40. }
  41. }

The final bit of tidying up we need to do is to move our gRPC handler code out into our new handler.go file. So let's do that.

  1. // shippy-service-consignment/handler.go
  2. package main
  3. import (
  4. "context"
  5. "log"
  6. pb "github.com/EwanValentine/shippy-service-consignment/proto/consignment"
  7. vesselProto "github.com/EwanValentine/shippy-service-vessel/proto/vessel"
  8. )
  9. type handler struct {
  10. repository
  11. vesselClient vesselProto.VesselServiceClient
  12. }
  13. // CreateConsignment - we created just one method on our service,
  14. // which is a create method, which takes a context and a request as an
  15. // argument, these are handled by the gRPC server.
  16. func (s *handler) CreateConsignment(ctx context.Context, req *pb.Consignment, res *pb.Response) error {
  17. // Here we call a client instance of our vessel service with our consignment weight,
  18. // and the amount of containers as the capacity value
  19. vesselResponse, err := s.vesselClient.FindAvailable(ctx, &vesselProto.Specification{
  20. MaxWeight: req.Weight,
  21. Capacity: int32(len(req.Containers)),
  22. })
  23. log.Printf("Found vessel: %s \n", vesselResponse.Vessel.Name)
  24. if err != nil {
  25. return err
  26. }
  27. // We set the VesselId as the vessel we got back from our
  28. // vessel service
  29. req.VesselId = vesselResponse.Vessel.Id
  30. // Save our consignment
  31. if err = s.repository.Create(req); err != nil {
  32. return err
  33. }
  34. res.Created = true
  35. res.Consignment = req
  36. return nil
  37. }
  38. // GetConsignments -
  39. func (s *handler) GetConsignments(ctx context.Context, req *pb.GetRequest, res *pb.Response) error {
  40. consignments, err := s.repository.GetAll()
  41. if err != nil {
  42. return err
  43. }
  44. res.Consignments = consignments
  45. return nil
  46. }

We've updated some of the return arguments in our repo slightly from the last tutorial:Old:

  1. type Repository interface {
  2. Create(*pb.Consignment) (*pb.Consignment, error)
  3. GetAll() []*pb.Consignment
  4. }

New:

  1. type Repository interface {
  2. Create(*pb.Consignment) error
  3. GetAll() ([]*pb.Consignment, error)
  4. }

This is just because I felt we didn't need to return the same consignment after creating it. And now we're returning a proper error from mgo for our get query. Otherwise the code is more or less the same.

Now let's do the same to your vessel-service. I'm not going to demonstrate this in this post, you should have a good feel for it yourself at this point. Remember you can use my repository as a reference.

We will however add a new method to our vessel-service, which will allow us to create new vessels. As ever, let's start by updating our protobuf definition:

  1. syntax = "proto3";
  2. package vessel;
  3. service VesselService {
  4. rpc FindAvailable(Specification) returns (Response) {}
  5. rpc Create(Vessel) returns (Response) {}
  6. }
  7. message Vessel {
  8. string id = 1;
  9. int32 capacity = 2;
  10. int32 max_weight = 3;
  11. string name = 4;
  12. bool available = 5;
  13. string owner_id = 6;
  14. }
  15. message Specification {
  16. int32 capacity = 1;
  17. int32 max_weight = 2;
  18. }
  19. message Response {
  20. Vessel vessel = 1;
  21. repeated Vessel vessels = 2;
  22. bool created = 3;
  23. }

We created a new Create method under our gRPC service, which takes a vessel and returns our generic response. We've added a new field to our response message as well, just a created bool. Run $ make build to update this service. Now we'll add a new handler in vessel-service/handler.go and a new repository method:

@todo - update

  1. // vessel-service/handler.go
  2. func (s *service) Create(ctx context.Context, req *pb.Vessel, res *pb.Response) error {
  3. if err := s.repository.Create(req); err != nil {
  4. return err
  5. }
  6. res.Vessel = req
  7. res.Created = true
  8. return nil
  9. }
  1. // vessel-service/repository.go
  2. func (repository *VesselRepository) Create(vessel *pb.Vessel) error {
  3. return repository.collection.Insert(vessel)
  4. }

Now we can create vessels! I've update the main.go to use our new Create method to store our dummy data, see here.

So after all of that. We have updated our services to use Mongodb. Before we try to run this, we will need to update our docker-compose file to include a Mongodb container:

  1. services:
  2. ...
  3. datastore:
  4. image: mongo
  5. ports:
  6. - 27017:27017

And update the environment variables in your two services to include: DB_HOST: "datastore:27017". Notice, we're calling datastore as our host name, and not localhost for example. This is because docker-compose handles some clever internal DNS stuff for us.

So you should have:

  1. version: '3.1'
  2. services:
  3. consignment-cli:
  4. build: ./consignment-cli
  5. consignment-service:
  6. build: ./shippy-service-consignment
  7. ports:
  8. - 50051:50051
  9. environment:
  10. MICRO_ADDRESS: ":50051"
  11. DB_HOST: "datastore:27017"
  12. vessel-service:
  13. build: ./shippy-service-vessel
  14. ports:
  15. - 50052:50051
  16. environment:
  17. MICRO_ADDRESS: ":50051"
  18. DB_HOST: "datastore:27017"
  19. datastore:
  20. image: mongo
  21. ports:
  22. - 27017:27017

Re-build your stack $ docker-compose build and re-run it $ docker-compose up. Note, sometimes because of Dockers caching, you may need to run a cacheless build to pick up certain changes. To do this in docker-compose, simply use the —no-cache flag when running $ docker-compose build.

User service

Now let's create a third service. We'll start by updating our docker-compose.yml file. Also, to mix things up a bit, we'll add Postgres to our docker stack for our user service:

  1. ...
  2. user-service:
  3. build: ./shippy-service-user
  4. ports:
  5. - 50053:50051
  6. environment:
  7. MICRO_ADDRESS: ":50051"
  8. ...
  9. database:
  10. image: postgres
  11. ports:
  12. - 5432:5432

Now create a user-service directory in your root. And, as per the previous services. Create the following files: handler.go, main.go, repository.go, database.go, Dockerfile, Makefile, a sub-directory for our proto files, and finally the proto file itself: proto/user/user.proto.

Add the following to user.proto:

  1. syntax = "proto3";
  2. package user;
  3. service UserService {
  4. rpc Create(User) returns (Response) {}
  5. rpc Get(User) returns (Response) {}
  6. rpc GetAll(Request) returns (Response) {}
  7. rpc Auth(User) returns (Token) {}
  8. rpc ValidateToken(Token) returns (Token) {}
  9. }
  10. message User {
  11. string id = 1;
  12. string name = 2;
  13. string company = 3;
  14. string email = 4;
  15. string password = 5;
  16. }
  17. message Request {}
  18. message Response {
  19. User user = 1;
  20. repeated User users = 2;
  21. repeated Error errors = 3;
  22. }
  23. message Token {
  24. string token = 1;
  25. bool valid = 2;
  26. repeated Error errors = 3;
  27. }
  28. message Error {
  29. int32 code = 1;
  30. string description = 2;
  31. }

Now, ensuring you've created a Makefile similar to that of our previous services, you should be able to run $ make build to generate our gRPC code. As per our previous services, we've created some code to interface our gRPC methods. We're only going to make a few of them work in this part of the series. We just want to be able to create and fetch a user. In the next part of the series, we'll be looking at authentication and JWT. So we'll be leaving anything token related for now. Your handlers should look like this:

// @todo - update

  1. // user-service/handler.go
  2. package main
  3. import (
  4. "golang.org/x/net/context"
  5. pb "github.com/EwanValentine/shippy/user-service/proto/user"
  6. )
  7. type service struct {
  8. repo Repository
  9. tokenService Authable
  10. }
  11. func (srv *service) Get(ctx context.Context, req *pb.User, res *pb.Response) error {
  12. user, err := srv.repo.Get(req.Id)
  13. if err != nil {
  14. return err
  15. }
  16. res.User = user
  17. return nil
  18. }
  19. func (srv *service) GetAll(ctx context.Context, req *pb.Request, res *pb.Response) error {
  20. users, err := srv.repo.GetAll()
  21. if err != nil {
  22. return err
  23. }
  24. res.Users = users
  25. return nil
  26. }
  27. func (srv *service) Auth(ctx context.Context, req *pb.User, res *pb.Token) error {
  28. user, err := srv.repo.GetByEmailAndPassword(req)
  29. if err != nil {
  30. return err
  31. }
  32. res.Token = "testingabc"
  33. return nil
  34. }
  35. func (srv *service) Create(ctx context.Context, req *pb.User, res *pb.Response) error {
  36. if err := srv.repo.Create(req); err != nil {
  37. return err
  38. }
  39. res.User = req
  40. return nil
  41. }
  42. func (srv *service) ValidateToken(ctx context.Context, req *pb.Token, res *pb.Token) error {
  43. return nil
  44. }

Now let's add our repository code:

  1. // user-service/repository.go
  2. package main
  3. import (
  4. pb "github.com/EwanValentine/shippy/user-service/proto/user"
  5. "github.com/jinzhu/gorm"
  6. )
  7. type Repository interface {
  8. GetAll() ([]*pb.User, error)
  9. Get(id string) (*pb.User, error)
  10. Create(user *pb.User) error
  11. GetByEmailAndPassword(user *pb.User) (*pb.User, error)
  12. }
  13. type UserRepository struct {
  14. db *gorm.DB
  15. }
  16. func (repo *UserRepository) GetAll() ([]*pb.User, error) {
  17. var users []*pb.User
  18. if err := repo.db.Find(&users).Error; err != nil {
  19. return nil, err
  20. }
  21. return users, nil
  22. }
  23. func (repo *UserRepository) Get(id string) (*pb.User, error) {
  24. var user *pb.User
  25. user.Id = id
  26. if err := repo.db.First(&user).Error; err != nil {
  27. return nil, err
  28. }
  29. return user, nil
  30. }
  31. func (repo *UserRepository) GetByEmailAndPassword(user *pb.User) (*pb.User, error) {
  32. if err := repo.db.First(&user).Error; err != nil {
  33. return nil, err
  34. }
  35. return user, nil
  36. }
  37. func (repo *UserRepository) Create(user *pb.User) error {
  38. if err := repo.db.Create(user).Error; err != nil {
  39. return err
  40. }
  41. }

We also need to change our ORM's behaviour to generate a UUID on creation, instead of trying to generate an integer ID. In case you didn't know, a UUID is a randomly generated set of hyphenated strings, used as an ID or primary key. This is more secure than just using auto-incrementing ID's, because it stops people from guessing or traversing through your API endpoints. MongoDB already uses a variation of this, but we need to tell our Postgres models to use UUID's. So in user-service/proto/user create a new file called extensions.go, in that file, add:

  1. package user
  2. import (
  3. "github.com/jinzhu/gorm"
  4. "github.com/satori/go.uuid"
  5. )
  6. func (model *User) BeforeCreate(scope *gorm.Scope) error {
  7. uuid := uuid.NewV4()
  8. return scope.SetColumn("Id", uuid.String())
  9. }

This hooks into GORM's event lifecycle so that we generate a UUID for our Id column, before the entity is saved.

You'll notice here, unlike our Mongodb services, we're not doing any connection handling. The native, SQL/postgres drivers work slightly differently, so we don't need to worry about that this time. We're using a package called 'gorm', let's touch on this briefly.

Gorm - Go + ORM

Gorm is a reasonably light-weight object relational mapper, which works nicely with Postgres, MySQL, Sqlite etc. It's very easy to set-up, use and manages your database schema changes automatically.

That being said, with microservices, your data structures are much smaller, contain less joins and overall complexity. So don't feel as though you should use an ORM of any kind.

We need to be able to test creating a user, so let's create another cli tool. This time user-cli in our project root. Similar as our consignment-cli, but this time:

  1. package main
  2. import (
  3. "log"
  4. "os"
  5. pb "github.com/EwanValentine/shippy/user-service/proto/user"
  6. microclient "github.com/micro/go-micro/client"
  7. "github.com/micro/go-micro/cmd"
  8. "golang.org/x/net/context"
  9. "github.com/micro/cli"
  10. "github.com/micro/go-micro"
  11. )
  12. func main() {
  13. cmd.Init()
  14. // Create new greeter client
  15. client := pb.NewUserServiceClient("go.micro.srv.user", microclient.DefaultClient)
  16. // Define our flags
  17. service := micro.NewService(
  18. micro.Flags(
  19. cli.StringFlag{
  20. Name: "name",
  21. Usage: "You full name",
  22. },
  23. cli.StringFlag{
  24. Name: "email",
  25. Usage: "Your email",
  26. },
  27. cli.StringFlag{
  28. Name: "password",
  29. Usage: "Your password",
  30. },
  31. cli.StringFlag{
  32. Name: "company",
  33. Usage: "Your company",
  34. },
  35. ),
  36. )
  37. // Start as service
  38. service.Init(
  39. micro.Action(func(c *cli.Context) {
  40. name := c.String("name")
  41. email := c.String("email")
  42. password := c.String("password")
  43. company := c.String("company")
  44. // Call our user service
  45. r, err := client.Create(context.TODO(), &pb.User{
  46. Name: name,
  47. Email: email,
  48. Password: password,
  49. Company: company,
  50. })
  51. if err != nil {
  52. log.Fatalf("Could not create: %v", err)
  53. }
  54. log.Printf("Created: %s", r.User.Id)
  55. getAll, err := client.GetAll(context.Background(), &pb.Request{})
  56. if err != nil {
  57. log.Fatalf("Could not list users: %v", err)
  58. }
  59. for _, v := range getAll.Users {
  60. log.Println(v)
  61. }
  62. os.Exit(0)
  63. }),
  64. )
  65. // Run the server
  66. if err := service.Run(); err != nil {
  67. log.Println(err)
  68. }
  69. }

Here we've used go-micro's command line helper, which is really neat.

We can run this and create a user:

  1. $ docker-compose run user-cli command \
  2. --name="Ewan Valentine" \
  3. --email="[email protected]" \
  4. --password="Testing123" \
  5. --company="BBC"

And you should see the created user in a list!

This isn't very secure, as currently we're storing plain-text passwords, but in the next part of the series, we'll be looking at authentication and JWT tokens across our services.

So there we have it, we've created an additional service, an additional command line tool, and we've started to persist our data using two different database technologies. We've covered a lot of ground in this post, and apologies if we went over anything too quickly, covered too much or assumed too much knowledge. Please refer to the git repo and as ever, please do send me your feedback!

If you are finding this series useful, and you use an ad-blocker (who can blame you). Please consider chucking me a couple of quid for my time and effort. Cheers! https://monzo.me/ewanvalentine

Or, sponsor me on Patreon to support more content like this.