paint-brush
Go Fast, Small, and Productive With GolangSpellby@danilovalente
500 reads
500 reads

Go Fast, Small, and Productive With GolangSpell

by Danilo ValenteNovember 22nd, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Before reading this article, make sure you have a good understanding of basic concepts of software development as Algorithms, Object Oriented design, Domain Driven Design. These will be the building blocks to digest the contents.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Go Fast, Small, and Productive With GolangSpell
Danilo Valente HackerNoon profile picture

Before reading this article, make sure you have a good understanding of basic concepts of software development as Algorithms, Object Oriented design, Domain Driven Design. These will be the building blocks to digest the contents.

Introduction to GoSpell

The Microservices architectural style appeared for the first time in 2005 and became a first class citizen in the architecture events in 2011, specially because of the successful Microservices based solutions presented at that time by Netflix and Amazon.

The core proposal suggests to structure the applications in a way in which it would be possible to deliver highly maintainable and adaptable systems in a loosely coupled and independently deployed fashion. In order to accomplish that, complex applications should be decomposed into smaller pieces aimed to encapsulate the features for an unique domain entity.

A Monolithic application decomposal can be used to explain the building blocks of the Microservices model.

MonolithicService

In the picture MonolithicService can be observed an example of Monolithic architecture, in which all of the application logic is coded, built and deployed as an unit. After refactoring this Monolith into Microservices, the result could be similar to the components presented in the picture Microservices.

Microservices

In the new design, there are independent components which obtain the same business logic through the exchange of messages between peers. This message exchange can be synchronous, (e.g. REST calls) or asynchronous (e.g. Event Streaming).

After having this high level introduction on the Microservices architectural model, it is easy to grasp that the performance and cost efficiency are a must when this architectural approach is selected.

The second solution is specially attractive when the performance and the operational cost of that is at least equivalent to the monolithic, with the advantage of being easily (and independently) scalable and easily extendable.

Golang

The Go language was designed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google and launched in 2009 as an open-source programming language.

The main goal of the project was to deliver a platform that was simple, easy to use and ready to address the common challenges in modern software development. The result was so efficient that it is largely used on Google and many other companies as a replacement for languages like C, C++ and Java.

With the language it is possible to create multi platform native applications, which means that a runtime environment is not necessary to execute the applications. This characteristic allows for delivering a Microservice running in a container with less than 20 MB, including the Operating System and the application itself. Even in runtime usually this does not go skyhigh after some minutes running (as would certainly happen in other platforms).

The performance is remarkable as well, the multithreading handling is simple and efficient by design delivering high velocity with a small footprint. In Cloud environments, in which horizontal scalability and computational resource usage efficiency is a must, it works like a Spell :)

In terms of Microservices development, with a very restrict set of dependencies it is very straightforward to have a new Go Microservice up and running.

Learning the details of Go is out of the scope of this article, but there is plenty of information available on that. These could be a good starting point:

Holy Reference: http://golang.org/ref/spec

Some useful patterns: http://golang.org/doc/effective_go.html

As in any other technology, there is always place for some valuable improvements. It can be noticed checking out some Golang applications, that there are not many similarities on how the code is organized. Basically each application is structured in a way that make sense for the application creators but hardly can be correlated with different applications, even inside the same team. While it can slightly reduce the design effort if we look to a single project, it certainly is not scalable in the long run. Inside a fast paced environment in which engineers come and go and the show must go on, having totally different structures all the time means that onboarding a new colleague can represent a huge effort. Building tools to make the life easier can be difficult as well, because it is totally unpredictable how the different applications will look like. Ruby on Rails, as a known very productive environment, took advantage of a more strict code structure to make it possible to deliver tools to deliver faster code following the same structure.

Golang Spell

Golang Spell is a productivity platform for building Microservices using Golang.

Golang Spell makes it possible to build lightning fast Microservices written Go in an easy and productive way. It is possible to generate the boilerplate code using Golang Spell, following a standard structure which can be shared between projects.

The platform was built using an approach of manageable code generation over code dependency. The library dependencies included in the generated applications are the minimum possible ones, to deliver clean and efficient code. A limited number of recognized frameworks are used for delivering the Microservice's core features:

The platform delivers several benefits, including:

It is an extendable platform. That means it is possible to create, publish and integrate new features as Spells, without the need of following any process from the Golangspell team to integrate it. The platform provides the features needed for extending it with new Spells;It provides a common platform where the community can build and share new Spells with the ability to create code to solve many different common problems;Speeds up dramatically the time to market generating the boilerplate code in an elegant fashion;It is Open Source and free for personal and commercial use;

How it works

The Golang Spell platform components starts with two core components, the golangspell tool and the golangspell-core Spell. The platform is totally based in plugins, called Spells in the platform context. The first Spell (golangspell-core), is automatically downloaded and installed when the golangspell tool is executed for the first time. It contains the core features of the platform. These features are responsible for initializing new Microservices, for creating new Spells, for adding new commands to Spells. It is important to understand the platform proposal while joining the community. The idea of the platform is not to add new features to the golangspell tool and the golangspell-core Spell. Instead of that, new specialized Spells should be created when needed. For example, for creating code related to MongoDB, there is another Spell, created using the Golangspell platform, which is responsible for delivering the MongoDB specific features, the golangspell-mongodb, which will be used on this article to create an example Microservice. The new Spells created by the community can be shared with the hole community in a public git repository or can be private, and not even be known by the Golangspell team. It is possible to directly integrate it locally using a private git repository.

The platform is command line based, composed by correlated CLI applications. On this tutorial this concepts will be presented in action in a real scenario building a Microservice which uses a MongoDB persistence layer.

Installation

The installation process is straightforward and based in the Golang tooling. The updated guided process can be found in the platform Wiki: https://github.com/golangspell/golangspell/wiki/QuickStart

The next steps are describing the installation process here, in the current state, to keep all the steps needed to accomplish the tutorial self contained.

Pre-reqs

Golang Installation

Git Installation

Recommended Tool

Visual Studio CodeVisual Studio Code Go Extension

Installing Golang Spell:

In order to install the Golang Spell tool use the command:

go install github.com/golangspell/golangspell@latest

Checking Golang Spell version

Let’s check if the Golangspell tool was properly installed using the command:

golangspell version

The current version at the article writing time is v0.4.3

Add binaries to Path

If the golangspell command is not found, it can be related with missing Path. In some operating systems (on Windows it is done automatically by the Golang installer package) it will be necessary to add the Golang’s bin directory to the path of your machine. This path corresponds to:

[YOUR GOPATH]/bin

where [YOUR GOPATH] stands for the path of the Golang installation in your machine.

The default Go path is

[YOUR USER DIRECTORY/go]

In a Mac computer it can be appended to the file /etc/paths

In my case I have added this line:

/Users/danilo/go/bin

After adding the path, the golangspell command will be available when you create a new terminal

Checking Golang Spell — Core Spell version

The Golang Spell automatically installs the Core Spell. The Spells are plugins which extend the tool capabilities with new features. The Golang Spell — Core Spell is a default Spell from the platform.

The Spell (plugin) version can be checked using the command :

golangspell version [Spell name])

To discover the current installed version of the golangspell-core spell the following command can be used:

golangspell version golangspell-core

The current version at the article writing time is v0.5.1

The help command shows the commands available in the golangspell tool.

golangspell help

The returned list of commands is composed by all the commands provided by the installed Spells. To run a command provided by any of the available Spells, the syntax will always start with:

golangspell [command]

In order to obtain the information for a specific subcommand, the syntax is:

golangspell help [command]

Build the first Microservice

The best way to learn how software works is using it. In this tutorial, you will learn how to build your first Go Microservice using Golang Spell.

User Story

As a Software Developer, I want to keep track of the projects in which I am working. I want to be able to configure the time unit to charge for the development and the unit price, so that I will have the reference to receive the payment for the development.

Concepts

Before to start coding the Microservice, it is important to understand the main concepts to be handled. It will make it easier the development afterwards and will ensure that we are delivering the features as expected.

In this case, after analysing the User Story, it was identified that the main concept to be handled by the Microservice is Project.

The Microservice created to manage the projects will be called project-api.

In the picture Components, can be found the components recommended to deliver the new features. For this tutorial, the cloud infrastructure and the frontend components are out of scope, the focus will be on the backend solution.

Components

Open API Specification

After having the domain concepts understood and the solution components defined, it is important to define the Interface Specification which will be used to define the contract which should be followed for the communication between the backend and frontend. This approach is known as Contract First. The Swagger Hub platform (https://swagger.io/tools/swaggerhub/) can be used to show and edit graphically the Open API specification. It is possible to create a free account there to try the platform with one user.

This is the Open API specification created for this article:

Join thousands of developers who use SwaggerHub to build and design great APIs. Signup or login today.app.swaggerhub.com

With the API specification defined, the next step is to define the Architectural Model and to create the Microservice.

Architectural Model

Before jumping to the code, it is important to do a link with the introduction section of the tutorial. There it was highlighted that it is a recommended practice, for many reasons, to adopt a standard structure which can be shared between multiple applications.

Many respected authors has given to us as a gift their suggestions, based on their personal experience with software development.

The Golang Spell platform is based in the Go ecosystem and it wouldn’t be reasonable to introduce complexity while trying to make things more standardized. This is why the chosen Architectural Model to be applied in the generated code is simple and effective by design, the Clean Architecture.

The Clean Architecture can be considered as an Architecture Guide, built up by Robert Martin

(as known in the Java Community as “Uncle Bob”) during his career, containing the main

recommended practices and patterns assembled and including ideas found in other architecture

models like Hexagonal Architecture, Onion Architecture, Screaming Architecture, DCI and BCE.

The model proposed in Clean Architecture promotes the application structuring by separating the business logic similarly to the way it is done when the engineering teams are understanding a new feature, in terms of use cases, domain entities and the related artifacts. By following correctly this architecture model it’s possible to achieve a clear responsibility division between the application’s layers.

In the next image can be observed the model proposed by Robert Martin.

Clean Architecture

In the next sections will be presented how the Clean Architecture was used as basis to structure the projects created with the Golang Spell platform.

Basically the tiers are separated in successive levels, containing artifacts with different abstraction levels. Moving from the inner concepts to the outer ones, we are moving from the business related logic to the tools and frameworks that support them.

An important aspect to note here is that, how can be noticed looking to the arrows direction, code references are allowed only from the outer levels to the inner levels. Backwards references are possible through inversion of control (injection).

The Golangspell applications are designed to be compliant with this Architectural Model, providing the organization and necessary features, like components injection, out-of-the-box.

Create application

Finally everything is set to build our first Microservice using Golang. This section will guide you through the steps needed to accomplish that task.

Firstly, let’s open a Terminal and create a new directory for the Microservice with the command:

mkdir project-api

or on Windows:

md project-api

Now, let’s jump inside the new directory with the command:

cd project-api

Now the magic is going to start… Use the next command to initialize the new Microservice code (don’t forget to replace [your-git-user] by your user name on Git):

golangspell init github.com/[your-git-user]/project-api project-api

The expected result is something like the following output:

Loading Spells …
Spells loaded!
Rendering template: .gitignore
Rendering template: Dockerfile
Rendering template: README.md
Rendering template: context.got
Rendering template: context_test.got
Rendering template: environment.got
Rendering template: logger.got
Rendering template: version.got
Rendering template: health_controller.got
Rendering template: health_controller_test.got
Rendering template: info_controller.got
Rendering template: info_controller_test.got
Rendering template: router.got
Rendering template: router_test.got
Rendering template: model_health.got
Rendering template: model_info.got
Rendering template: logger.got
Rendering template: main.got
Rendering template: .gitkeep
go: creating new go.mod: module github.com/[your-git-user]/project-api
Application created!
— — — — — — — — — — — — — — — — — — — — — — — — — — — — -
To run your application, first build it with the command:
go build
— — — — — — — — — — — — — — — — — — — — — — — — — — — — -
Then execute the application with the command (Unix based systems):
./project-api
Then execute the application with the command (Windows based systems):
project-api
— — — — — — — — — — — — — — — — — — — — — — — — — — — — -
Available endpoints:
http://localhost:8080/project-api/v1/info
http://localhost:8080/project-api/v1/health
— — — — — — — — — — — — — — — — — — — — — — — — — — — — -
Find more details on README.md file

Let’s follow the recommendation and try to build the application with the command:

go build

Now we can run the application using the command:

./project-api

or simply this on Windows:

project-api

Here the expected result is something like:

This result means that the application is currently running in the local environment in the port 8080.

We can check it out in the suggested endpoints, http://localhost:8080/project-api/v1/health

and

http://localhost:8080/project-api/v1/info

This two endpoints provides respectively the health check result and the current version of the application (the version is configured in the generated file config/version.go).

The application now can be stopped in the terminal using the key combination Ctrl + C;Let’s open the application folder using Visual Studio Code (or your preferred editor) to discover and understand the generated code. To do that, open the Visual Studio Code, click in File -> Open and select the directory created for your application. The application will be shown:

Project view

In the README.md file can be found some hints on how to build, run the tests and the lint for the new project.

Now we can proceed to understand the other generated package and files.

Tip: Make sure that the Go Extension is installed in the Visual Studio Code to make your life easier, like suggested in the Installation Process - Recommended Tool

Packages

In this section will be presented the generated packages and respective files.

Package appcontext

This package maintains the Application Context logic.

The ApplicationContext is responsible for keeping the current instances of the application’s components.

Using the ApplicationContext is possible to inject dependencies using interfaces, keeping the design consistent with the Clean Architecture. The dependency injection is important to make it easier to test the application components (this way mocking becomes trivial).

File context.go

Contains the application context implementation. In this file can be found the logic for lazy loading the components in the first usage is in the ApplicationContext. Additionally, in this file are defined the constants created in order to make it possible to identify the available components in the context.

File context_test.go

As expected, this file contains the tests of the ApplicationContext.

Package config

The package config contains the application configuration files.

File environment.go

As the name suggests, this file manages the environment variables used inside the application.

File logger.go

As you can guess, this file contains the Logger definitions. It provides the Logger interface, which defines the Logger capabilities, and the utility function GetLogger(), which gets the current Logger instance.

File version.go

As stated previously, this file maintains the application version number.

Package controller

The package controller contains the application controllers and routing logic. The REST framework Echo (https://echo.labstack.com/) is used for handling the HTTP interactions in the router and in the controllers.

File router.go

The file router.go contains the HTTP routing logic.

Files with the suffix _controller.go

The files with the suffix _controller.go, contains the controller layer code. They handle the HTTP requests generating the proper responses.

Package domain

The package domain contains the domain entities. The domain entities are meant for keeping the business domain data and the core related business rules. In the domain package are defined as well the interfaces used to inject the components defined in the other layer like gateways, for example.

Files with prefix model_

The domain entities are coded in files with the names starting with the prefix model_. One file should be created for holding each domain entity logic.

Package gateway

The package gateway contains the specific packages for the components which represents the interfaces with the external actor with which the application interacts, like databases, cache, queues and services.

Package customlog

This package contains the current log implementation of the interface defined in the config package.

File logger.go

Contains the implementation of the Logger struct.

Package usecase

This package contains the usecases, which defines the workflows needed to deliver the application’s business features.

Files in the root directory

Dockerfile

Contains the logic for building an alpine image with the application. During the build process, the tests are executed to make sure that the code is not broken.

go.mod

The file go.mod keeps the module name and the application dependencies. The dependency management is done using Go Modules.

main.go

This file starts up the application and keeps the static imports to make sure that the all the packages will be initialized.

CRUD for the domain entity Project

Now is time to add to the application the CRUD (Create, Read, Update and Delete) features.

The persistence choice for this Microservice is Mongodb.

Using a Nosql database is a good choice for having scalability and a flexible schema in a single shot, powered by a cloud managed service.

There are multiple mongodb as a service options, which means no vendor lock-in and a lot of documentation available. It can be executed in containers as well if needed.

In this article the database will be executed locally as a container. In order to run the local Docker image, the following command can be used:

docker run -d -p 27017:27017 mongo

The next command will configure the connection string for the database:

export DB_CONNECTION_STRING=”mongodb://localhost:27017/project”

or, on Windows:

set DB_CONNECTION_STRING=”mongodb://localhost:27017/project”

Now the database is up and running and the connection string is set in the terminal. It is time to install the next spell which will be used to create the CRUD implementation, the golangspell-mongodb. The next command will do it:

golangspell addspell github.com/golangspell/golangspell-mongodb golangspell-mongodb

Now there will be additional commands in the platform, as can be noticed with the command:

golangspell help

We are interested in the command mongodbinit. Let’s know more about the syntax using the command:

golangspell help mongodbinit

This command initializes the application with the Mongodb infrastructure.

Let’s create a new Mongodb persistence infra, including a new database called project (the database name is the last word in the command). In order to accomplish that, the following command must be used:

golangspell mongodbinit project

After the command execution some changes can be observed in the project:

Project with the MongoDB infrastructure

Firstly, a new package was created, called mongodb, inside the gateway package.

On this package was created a new file, called db_client.go. This file contains a client component to communicate with the mongodb database called project.

The second change can be noticed in the config package. The file environment.go now have a backup file, with the same name and a suffix _backup_<timestamp>. The backup is done automatically when an application file is changed by a Spell command.

Comparing the backup file and the current environment.go file, can be noticed that two new environment variables were added to connect to the mongodb database, DB_CONNECTION_STRING and DB_CONNECTION_CERTIFICATE_FILE_NAME. This variables can be accessed in the application code through the variables config.Values.DBConnectionString and config.Values.DBConnectionCertificateFileName respectively. The first one defines the connection string and the second one defines the certificate file name if the connection is using TLS.

The third change is in the package appcontext. The file context.go was changed and backed up as well, because a new constant was introduced to define the new component added to the application context, DBClient.

Looking at the file db_client.go, there is an example of how to register a component in the application context. It is done in the application lifecycle during the initialization process, this is why the command appcontext.Current.Add(appcontext.DBClient, buildMongoClient) is implemented in the init() function.

This command adds to the application context the new DBClient component, providing as parameters:

appcontext.DBClient: the constant defined to identify the new component buildMongoClient: the method which will be used to lazy load the component in the first time it is used.

At this point the application has the Mongodb infrastructure available and is ready for receiving the CRUD implementation. In order to create that, the next command to execute is:

golangspell mongodbaddcrud Project

As can be seen with the help of the golangspell help mongodbaddcrud command, the unique expected parameter is the domain entity name, in camel case. In our example the business entity which will be represented is the Project, so that the provided name will be Project.

After the command execution some changes can be observed in the project:

Application with the base CRUD code

A new backup was created to the file appcontext/context.go. That means some changes were made to the file. Some constants were added, referring to the new components created in the application. These components are:

ProjectRepository: The Repository created to handle the persistence features for the new domain. The implementation of the component can be found in the new file gateway/mongodb/project_repository.go;

ProjectDeleteUsecase: The use case created for the feature Project — Delete. The implementation of the component can be found in the new file usecase/project_delete_usecase.go;

ProjectUpdateUsecase: The use case created for the feature Project — Update. The implementation of the component can be found in the new file usecase/project_update_usecase.go;

ProjectGetByIDUsecase: The use case created for the feature Project — Get By Id. The implementation of the component can be found in the new file usecase/project_get_by_id_usecase.go;

ProjectGetAllUsecase: The use case created for the feature Project — Get All. The implementation of the component can be found in the new file usecase/project_get_all_usecase.go;

ProjectCreateUsecase: The use case created for the feature Project — Create. The implementation of the component can be found in the new file usecase/project_create_usecase.go;

The backup of the file controller/router.go indicates that something was changed there. Looking to the new state of the file it is possible to notice that new HTTP routes were added. These new routes exposes the Project management endpoints.

A new file called controller/project_controller.go was created as well with the logic to handle the Project endpoints requests.

The business domain entity can be found in the new file domain/model_project.go.

In this new file can be found:

The struct which represents the business entity. The struct is generated with the following attributes:

ID — Instance Identifier;

DateCreated — timestamp which holds the creation date;

DateUpdated: timestamp representing the last update date;The interface which specifies the Repository capabilities;

The interfaces which represents the Use Cases related to the business entity;

The convenience functions to retrieve the current implementation of the related components, loaded in the application context during the initialization phase.

The component abstraction using interfaces and the application context makes it easier to build tests with mocked components using tools like Mockery (https://github.com/vektra/mockery).

The Rhymond/go-money (https://github.com/Rhymond/go-money) library will be used in this article for managing the monetary amounts. This way we will have a better monetary amounts precision. In order to accomplish this, it is necessary to create a wrapper struct to persist the monetary data in the database. Let’s create a new file called model_money.go inside the package domain and paste the following code:

Golang Spell MongoDB example project. Contribute to danilovalente/project-api development by creating an account on…github.com

Some additional attributes must be added to the file domain/model_project.go to represent properly the model defined in the Open API Specification.

Add the current attributes to adjust it accordingly:

Name string `bson:”name” json:”name”`
UnitPrice Money `bson:”unitPrice” json:”unitPrice”`
TimeUnit string `bson:”timeUnit” json:”timeUnit”`

Add the following code to the Valid() method, in order to check if the instance state is valid:

if project == nil {
return false, ConstraintViolation(“The Project is not instantiated”)
}
if strings.TrimSpace(project.Name) == “” {
return false, ConstraintViolation(“The Project is invalid. The required attribute ‘Name’ is missing”)
}
if project.UnitPrice.IsZero() || project.UnitPrice.IsNegative() || strings.TrimSpace(project.UnitPrice.Currency) == “” {
return false, ConstraintViolation(“The Project is invalid. The ‘Unit Price’ must be in a valid Currency and must be greater than zero”)
}
if project.TimeUnit != “Hour” &&
project.TimeUnit != “Day” &&
project.TimeUnit != “Week” &&
project.TimeUnit != “Month” {
return false, ConstraintViolation(“The Project is invalid. The ‘TimeUnit’ must be any of [Hour, Day, Week, Month]”)
}
return true, nil

After this changes, the code in the file domain/model_project.go will look like this:

Golang Spell MongoDB example project. Contribute to danilovalente/project-api development by creating an account on…github.com

After adding this code the Microservice is ready for being used.

The following flow will be executed when the application receives a request pointing to the Create Project endpoint:

Request processing sequence

Now it is time to test the Microservice running with the new features.

Firstly, let’s build again the application using the command:

go build

Now we can execute the application using the command:

./project-api

(or simply project-api on Windows)

The API is running!

Now it is possible to test the application using REST calls.

Let’s start with the creation of a new project with this command:

curl -X POST “http://localhost:8080/project-api/v1/project" -H “accept: application/json” -H “Content-Type: application/json” -d “{\”name\”:\”My Customer Project\”,\”unitPrice\”:{\”currency\”:\”EUR\”,\”amount\”:70000},\”timeUnit\”:\”Day\”}”

The command will create a new Project document in the database. The expected results are the contents of the created document:

{“id”:”5f175f8780254962243c9362",”name”:”My Customer Project”,”unitPrice”:{“amount”:70000,”currency”:”EUR”},”timeUnit”:”Day”,”dateCreated”:”2020–07–21T23:35:03.104716+02:00",”dateUpdated”:”0001–01–01T00:00:00Z”}

In my response, for example, a new document was created with the id 5f175f8780254962243c9362. This Id will be used in the next commands to refer to this document. Change this to the one returned for you in the next commands.

Following with the usage example, lets get all the documents in the collection with the command:

curl -X GET “http://localhost:8080/project-api/v1/project" -H “accept: application/json”

The command returns an array of Projects. For getting only an specific document, by Id:

curl -X GET “http://localhost:8080/project-api/v1/project/5f175f8780254962243c9362" -H “accept: application/json”

Now, let’s update the document increasing the price from 700 Euros to 850 Euros (the amount notation is made by the value multiplied by 100, to include the cents in an int value):

curl -X PUT “http://localhost:8080/project-api/v1/project/5f175f8780254962243c9362" -H “accept: application/json” -H “Content-Type: application/json” -d “{\”id\”:\”5f175f8780254962243c9362\”,\”name\”:\”My Customer Project\”,\”unitPrice\”:{\”currency\”:\”EUR\”,\”amount\”:85000},\”timeUnit\”:\”Day\”}”

Now the last test will be to delete the document from the database with the command:

curl -X DELETE “http://localhost:8080/project-api/v1/project/5f175f8780254962243c9362" -H “accept: application/json”

Executing again the get all command nothing will be returned:

curl -X GET “http://localhost:8080/project-api/v1/project" -H “accept: application/json”

The get all command is ready for pagination as well. It accepts the query parameters pageSize (int) and lastProjectId (ObjectId, 5f175f8780254962243c9362 for example). If these parameters are defined like this:

curl -X GET “http://localhost:8080/project-api/v1/project?pageSize=10&lastProjectId=5f175f8780254962243c9362" -H “accept: application/json”

… will be returned the next 10 documents with id greater than 5f175f8780254962243c9362. The id based pagination delivers a very good performance in Mongodb.

Now you can play around with your first Microservice built with Golangspell, using the examples as a reference.

The project generated during the article can be found here: https://github.com/danilovalente/project-api

In normal situations the files with extensions like “go_backup_[timestamp]” should be deleted instead of added to the code repository. They are in the repository only for showing the intermediate steps of the project code.

Conclusion

In this article were presented:

  • Microservices development context;
  • Golangspell platform fundamentals;
  • Steps needed to install the Golangspell platform and the golangspell-mongodb spell;
  • Steps needed to create the first full featured Microservice using the Golangspell platform.

The outcome of these steps is a structured application following the Clean Architecture principles and ready for being extended using other Golangspell features. The generated code is organized into logic layers in an intuitive, maintainable and extendable fashion.

Probably you could notice in your testing that an additional (and awesome!) benefit is the performance of the application. The relationship between the response time and the very small footprint is unbeatable (for now…).

Now having a very good productivity is one go get away from you with the Golangspell platform, enjoy!

Please find more information here:

Project Wiki

https://github.com/golangspell/golangspell/wiki

Project Group

https://groups.google.com/d/forum/golangspell

Looking forward to receive your feedback and to proceed bringing new features!

Also published at https://medium.com/golangspell-go-fast-small-and-productive/go-fast-small-and-productive-with-golangspell-be193c65a382