Building Server-side and Microservices with Go: Building Modern Backends and Microservices Using Go, Docker and Kubernetes
()
About this ebook
We will create simple server-side applications and add new features as and when a new topic is covered. We will begin with the fundamentals of Go programming languages, which will create simple server-side applications. During development, a layered design will be introduced, with each application layer serving a specific purpose. We will introduce you to the microservice concept, and it is further divided into a couple of smaller microservices. Finally, we'll look at how to use Docker and Kubernetes to deploy and scale microservices.
After reading this book, we will be able to successfully develop monolithic and microservice applications and identify when one approach is more appropriate than another. This book can also help improve existing applications. It is a perfect handy guide to build proficiency with Docker and Kubernetes.
Related to Building Server-side and Microservices with Go
Related ebooks
Learning Go Programming: Build ScalableNext-Gen Web Application using Golang (English Edition) Rating: 0 out of 5 stars0 ratingsMonitoring Docker Rating: 0 out of 5 stars0 ratingsModern Web Development with Go: Build real-world, fast, efficient and scalable web server apps using Go programming language Rating: 0 out of 5 stars0 ratingsLearning Elasticsearch 7.x: Index, Analyze, Search and Aggregate Your Data Using Elasticsearch (English Edition) Rating: 0 out of 5 stars0 ratingsHands-On System Design: Learn System Design, Scaling Applications, Software Development Design Patterns with Real Use-Cases Rating: 0 out of 5 stars0 ratingsDesigning Microservices using Django: Structuring, Deploying and Managing the Microservices Architecture with Django Rating: 0 out of 5 stars0 ratingsBuilding Decentralized Blockchain Applications: Learn How to Use Blockchain as the Foundation for Next-Gen Apps (English Edition) Rating: 0 out of 5 stars0 ratingsNetwork Programming in Python : The Basic: A Detailed Guide to Python 3 Network Programming and Management Rating: 0 out of 5 stars0 ratingsArt of Clean Code: How to Write Codes for Human Rating: 3 out of 5 stars3/5Introduction to DBMS: Designing and Implementing Databases from Scratch for Absolute Beginners Rating: 0 out of 5 stars0 ratingsHands-On Parallel Programming with C# 8 and .NET Core 3: Build solid enterprise software using task parallelism and multithreading Rating: 0 out of 5 stars0 ratingsDeveloping with Docker Rating: 5 out of 5 stars5/5Software Design Patterns for Java Developers: Expert-led Approaches to Build Re-usable Software and Enterprise Applications Rating: 0 out of 5 stars0 ratingsLearning Docker - Second Edition Rating: 0 out of 5 stars0 ratingsGo Programming Blueprints Rating: 0 out of 5 stars0 ratingsThe Way to Go: A Thorough Introduction to the Go Programming Language Rating: 2 out of 5 stars2/5Go Programming Blueprints - Second Edition Rating: 5 out of 5 stars5/5Tanmay Teaches Go: The Ideal Language for Backend Developers Rating: 0 out of 5 stars0 ratingsMicroservices by Examples Using .NET Core: Using .NET Core Rating: 0 out of 5 stars0 ratingsHow To Build Microservices: Top 10 Hacks To Modeling, Integrating & Deploying Microservices Rating: 0 out of 5 stars0 ratingsHands-On Microservices with Kubernetes: Build, deploy, and manage scalable microservices on Kubernetes Rating: 5 out of 5 stars5/5Learn Rust Programming: Safe Code, Supports Low Level and Embedded Systems Programming with a Strong Ecosystem (English Edition) Rating: 0 out of 5 stars0 ratingsCloud Native Patterns: Designing change-tolerant software Rating: 4 out of 5 stars4/5
Robotics For You
Robot Building For Dummies Rating: 3 out of 5 stars3/5Become a U.S. Commercial Drone Pilot Rating: 5 out of 5 stars5/5Artificial Intelligence: The Complete Beginner’s Guide to the Future of A.I. Rating: 4 out of 5 stars4/5Dark Aeon: Transhumanism and the War Against Humanity Rating: 5 out of 5 stars5/5Raspberry Pi Projects for the Evil Genius Rating: 0 out of 5 stars0 ratingsThe Fourth Age: Smart Robots, Conscious Computers, and the Future of Humanity Rating: 3 out of 5 stars3/5Arduino: The complete guide to Arduino for beginners, including projects, tips, tricks, and programming! Rating: 4 out of 5 stars4/5Artificial Intelligence Revolution: How AI Will Change our Society, Economy, and Culture Rating: 5 out of 5 stars5/5How to Walk on Water and Climb up Walls: Animal Movement and the Robots of the Future Rating: 3 out of 5 stars3/5101 Spy Gadgets for the Evil Genius 2/E Rating: 4 out of 5 stars4/5CNC: How Hard Can it Be Rating: 4 out of 5 stars4/5How to Build an Android: The True Story of Philip K. Dick's Robotic Resurrection Rating: 4 out of 5 stars4/5ChatGPT: The Future of Intelligent Conversation Rating: 4 out of 5 stars4/5Robotics, Mechatronics, and Artificial Intelligence: Experimental Circuit Blocks for Designers Rating: 5 out of 5 stars5/5Artificial You: AI and the Future of Your Mind Rating: 4 out of 5 stars4/515 min Book Summary of Martin Ford's Book "The Rise of the Robots": The 15' Book Summaries Series, #5 Rating: 5 out of 5 stars5/5Machine Learning: Adaptive Behaviour Through Experience: Thinking Machines Rating: 4 out of 5 stars4/5How to Survive a Robot Uprising: Tips on Defending Yourself Against the Coming Rebellion Rating: 3 out of 5 stars3/5In Our Own Image Rating: 4 out of 5 stars4/5Building with Virtual LEGO: Getting Started with LEGO Digital Designer, LDraw, and Mecabricks Rating: 0 out of 5 stars0 ratingsThe Truth About Santa: Wormholes, Robots, and What Really Happens on Christmas Eve Rating: 3 out of 5 stars3/5Turned On: Science, Sex and Robots Rating: 4 out of 5 stars4/52062: The World that AI Made Rating: 5 out of 5 stars5/5Introducing Artificial Intelligence: A Graphic Guide Rating: 3 out of 5 stars3/5Raspberry Pi: The complete guide to raspberry pi, including raspberry pi projects, tips, troubleshooting, and more! Rating: 0 out of 5 stars0 ratings
Reviews for Building Server-side and Microservices with Go
0 ratings0 reviews
Book preview
Building Server-side and Microservices with Go - Dušan Stojanović
CHAPTER 1
Fundamentals of Go Programming Language
In this chapter, we will explain the basic concepts of Go programming language. That includes variables, constants, data types, flow control statements, functions, methods, interfaces, and concurrency. With the knowledge learned in this chapter, we can write any program and application in Go programming language.
Structure
In this chapter, we will discuss the following topics:
History of Go
Installation
Basics of Go
First Go Program
Packages
Variables
Constants
Comments
Data types
Basic types
Type conversion
Pointers
Struct
Arrays
Slices
Maps
Flow control
For loop
Range
If and if-else
Switch
Defer
Functions and Methods
Functions
Methods
Interfaces
Concurrency
Goroutines
Channels
Select
Mutex
WaitGroups
Scheduling in Go
Garbage Collector
Testing
Objectives
After studying this unit, you should be able to:
Understand the concepts of Go programming language
Write any kind of Go applications
1.1 History of Go
Go is a programming language designed at Google by Rob Pike, Robert Griesemer and Ken Thompson in 2007. Because of the official language domain golang.org, Go is often called Golang.
Syntactically, Go is similar to C, but many "features" are borrowed from other languages. The structure of programs and declaration structure is similar to Oberon (in declaration structures name always comes first, then type, in C type comes first then name). Some concurrency aspects (channels, select statement) are taken from Newsqueak. All features will be explained later, with some useful examples.
The official logo is a stylized, italic GO with trailing streamlines that resemble two wheels in motion, symbolizing speed and efficiency. The logo is presented in April 2018. Gopher (rodent from North and Central America) is an official mascot of language.
Many modern-day languages, like C++, C#, or Java, are fast but usually they are too complex and development unfriendly. Scripting languages (PHP, Ruby, JS,…) are created to be more development friendly but they are slow and unsafe. Go combines best from two worlds; it is fast safe and development friendly.
Go is designed to be simple as possible, but powerful enough to solve all modern-day problems. Go is not Object Oriented (like Java or C++), you do not have classes and heritage, but that is not a problem. You can use it to write any kind of software solution, for example, REST API, Microservices, Desktop Applications (fine-io), even Arduino and Microprocessors can be programmed in Go (tinygo).
In this book we will see how we can create a simple REST API Service, and how can we split it into smaller Microservices.
1.2 Installation
You can download Go distribution from golang.org website. Choose suitable version for your OS (Windows, Linux, or macOS). If you want you can the download source also.
For Linux systems, download the archive and extract it into /usr/local directory. This will create new directory/usr/local/go. In order to work properly, you need to add /usr/local/go/bin to the PATH environment variable.
For macOS systems, download the package file and install Go distribution. The package will install it into /usr/local/go directory. The package should put/usr/local/go/bin in PATH environment variable.
For Windows systems, there are two options. You can download MSI file or zip archive. If you prefer the first option just follow the instructions and Go distribution will be installed. By default, installer should put Go distribution in c:/go folder and c:/go/bin in PATH environment variable.
If you choose to download zip archive, when the download is finished extract the archive into folder (the best option is c:/go) and add c:/go/bin in PATH environment variable.
After installation, in the terminal, execute the following command:
go version
The result will be output similar to:
go version go1.13.3 windows/amd64
Tip: If terminal sessions are opened during installation of Go distribution, command may not be executed. Restart of all opened terminal sessions should fix the problem.
You can write Go code in any text editor, but it easier to choose proper integrated development environment (IDE). Jetbrains GoLand is IDE build specially for Go developers. You can download 30-day free trial version from jetbrains.com/go.
Visual Studio Code is free open-source solution. You can download the newest version from code.visualstudio.com. After IDE installation you must add Go extension. Choose View, Extensions, and types go
in the search bar. Select Go or Go Nightly extension and install it. After installing Visual Studio Code is now ready.
1.3 Basics of Go
In order to create even the simplest programs, basic concepts of programming language should be learned and adopted. Everything that we need to successfully write programs with Go will be covered in following sections.
1.3.1 First Go program
When everything is set up we can write our first program. As a usual first example for any programming language is Hello World
.
All go files have .go extension, so here is the content of helloworld.go file.
package main
import fmt
func main() {
fmt.Println(Hello World!!!
)
}
This small program will print "Hello world!!!" on standard output (terminal). One interesting thing that you can spot right away, you do not need to put semicolon at the end of the statement. Go designers tried to reduce the usage of semicolons to make the code cleaner. You can write semicolons at the end of statements but they will be ignored.
We can compile the program with command:
go build helloworld.go
This command will create an executable file that we can run.
We can use run command, which will compile and run the program without the creation of an executable file:
go run helloworld.go
Let us look at more details and further clarify the program.
1.3.2 Packages
All go programs are made of packages. Name of the package is (usually) the first line in file. In "Hello World" example line package main indicates that file belongs to the main package. All go programs start running from the main package.
We can import things from other packages using import keyword. In "Hello World" example fmt package has been imported. This package contains functions that allow us to display data on standard output.
We can import more than one package. For example, we can import fmt and math packages.
import fmt
import math
Or we can use factored import statement.
import (
fmt
math
)
It is considered good practice to use the factored import statement.
We can export names from package. Name is exported if begins with capital letter. In example below Two and Add() are exported, one and sub() are not exported from package namesexport.
package namesexport
var one = 1
var Two = 2
func Add(a, b int) int {
return a + b
}
func sub(a, b int) int {
return a - b
}
All not exported names are not available outside the package. When the package is imported we can access only to its exported names.
1.3.3 Variables
Variables are symbolic names associated with the value that may be changed. We can use var keyword to declare the variable. After var keyword, we specify variable name or list of names and type comes at the end. Variable can be global, accessible in whole package or local, accessible only in function where is declared. In example, below we can see how to declare local and global variables.
package main
import fmt
var globalA int
var globalB = 1
func main() {
var localA int
var localB, localC int = 2, 3
fmt.Println(globalA, globalB, localA, localB, localC)
}
We can initialize variables in var declaration. We must have the same number of initializers as variable names. In the previous example, we have two variable names in the list (localB and localC) so we must have two values after sign of equality. If the initializer is present we can omit type. In that case, variable will take type of initializer. In previous example, globalB will become integer.
Go takes short assignment statement := from Newsqueak. We can use this statement to replace var statement with initialization. These two statements are the same:
var a int = 1
a := 1
Short assignment statement can be used only inside functions (outside functions all statements must begin with keyword). Global variables cannot be declared with this statement.
1.3.4 Constants
Constants are declared similar to variables with keyword const in front. Once assigned valued cannot be changed. Constants cannot be declared with short assignment (:=). This statement will create a constant Pi that can be used in other parts of code.
const Pi = 3.1415927
1.4 Comments
Often, we write comments to give more detailed explanation for part of our code. Comments are not an executable part of code and will be ignored by the compiler. Go offers two types of comments.
Single-line comments are used for short, one-line comments. Everything after // (double slash) and end of the line will be ignored by the compiler and considered a comment.
Multi-line comments: For longer comments (comments in more than one line) we can use multi-line comments. Everything between /* (slash and asterisk) and */ (asterisk and slash) will be ignored by compiler and considered a comment.
Here are examples of on line and multi-line comments.
// This is single line comment
/* This is
multi line comment /*
1.5 Data types
Data types define possible values that variables can have and operations that can be performed. As most programming languages, Go support basic data types (integer numbers, floating point numbers, etc) and complex data types (arrays, maps, etc). We will cover all supported types whit more details.
1.5.1 Basic types
Go support following basic data types:
Integers (whole numbers) are numbers that can be written without a fractional component. Go basic types for integers are int, int8 (set of all 8 bit signed integers), int16 (set of all 16 bit signed integers), int32 (set of all 32 bit signed integers) and int64 (set of all 64 bit signed integers). The int is 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
Unsigned integers (natural numbers) are set of non-negative integer values. Go basic types for unsigned integers are uint, uint8 (set of all 8-bit unsigned integers), uint16 (set of all 16-bit unsigned integers), uint32 (set of all 32-bit unsigned integers), unit64 (set of all 64-bit unsigned integers) and uintptr. The uint is 32 bits wide on 32-bit systems and 64 bits on 64-bit systems. The uintptr is integer type large enough to hold the bit pattern of any pointer.
Floating-point numbers (real numbers) are numbers that can be written with decimal points dividing integer and fractional components. Go basic types for floating-point numbers are float32 (32-bit floating-point numbers) and float64 (64-bit floating-point numbers).
Complex numbers are numbers that can be expressed in the form a + bi, where a and b are real numbers and i is a solution of equation x2 = -1. Because i is not real number it is called the imaginary number, a is called real part and b is called imaginary part. Basic Go types for complex numbers are complex64 (set of all complex numbers with float32 real and imaginary parts) and complex128 (set of all complex numbers with float64 real and imaginary parts).
The byte is a unit of digital information consisting of 8 bits. Go has a basic type byte that can be used to distinguish byte from other integers type. The byte is just an alias for uint8 and is equivalent with it in all ways. If you want you can use uint8 for bytes, the effect will be the same.
Rune : Often, developers have a problem with Unicode characters. For example, in C family of programming languages char type is 8-bit wide, but Unicode characters are (usually) 16-bit wide. Go has basic type rune for Unicode characters. Similarly to byte, rune is alias for int32.
Boolean data type is used for logical operations and can have one of two possible values (true or false). The basic type for boolean values is bool.
String is type that represents the sequence of alphanumeric text or other symbols. In our "Hello World example, printed text (
Hello World!!!") represents one string. Go has a string basic type.
All basic types have default values. If we declare variable without an initializer, the default value will be given to the variable. For numeric values 0 is default value, false is default value for bool and
(empty string) is default value for string.
Note: In Go related literature and documentation term zero value
is often used instead of the term default value
1.5.2 Type conversion
In many programming languages, there is an implicit conversion. If we try to assign integer value 5 to float variable, the value will be converted to 5.0 and assigned to variable. In Go, assignment of different types requires explicit conversion.
We use expression Type(value) to convert the selected value to the desired type. This statement will convert integer value 5 to float32 and assign value to floating point variable.
var f float32 = float32(5)
1.5.3 Pointers
Pointer is data types that hold the memory address of a value. The default value for pointer is nil. We can declare pointer variable by adding asterisk before type.
var pi *int
This is an integer pointer. We can create pointer to any type of value.
Figure 1.1 represents small part of memory with 4 memory addresses (0 to 3). Pointer pi is saved on address 1, integer i is saved on memory address 3. For now value of pointer is nil, value of variable i is 8 (Figure 1.1a).
We have two pointer operators. The first operator & (ampersand) is used to find the address of variable. We can use this operator to initialize value for pointer.
var pi = &i
Now, pointer pi will have value of address of variable i (3 in our example, Figure 1.1b).
The second operator * (asterisk) can give us access to value pointer points to. We can use this operator to change the pointed value.
*pi = 5
Integer pointer will now point to value 5 (Figure 1.1c) but with this statement value of variable i is also changed. If we print value i on standard output, value 5 will be displayed:
Figure 1.1: Pointers and variables in memory
Here is the complete code for this example:
package main
import fmt
func main() {
var i int = 8
var pi *int
pi = &i
*pi = 5
fmt.Println(i)
}
Pointers can be very useful when we work with complex data types. We don't need to create many copies of the same complex object in memory, we can just pass the pointer. But we must be very careful when working with pointers not to cause any unwanted changes on pointed objects.
Some programming languages, like C, have pointer arithmetic so you can perform simple arithmetic operations on pointers. Go is designed without pointer arithmetic.
1.5.4 Struct
Struct is the complex data type and represents the collection of fields. We use type keyword to declare struct. After type keyword, we specify struct name and keyword struct comes at the end. Between curry bracket, we declare fields with field name and type. In the example below, we declared struct Circle with three fields, coordinates of center X and Y and radius R.
We use operator .(dot) to access struct fields (similar to accessing fields and methods in object-oriented programming languages). Also, we can use struct pointer to access fields. If we follow all pointer rules, to access field R of Circle struct, from our example, through pointer p, our statement should look like this:
(*)p.R
But this statement is too bulky and complex and we see previously, Go is designed to be simple as possible. So in order to avoid this "ugly" code, Go designers decided to allow user to write simple statement
p.R
To access struct field through pointer.
When we create new struct we don’t need to specify values for all fields. For all fields without value, default value will be assigned. In example below, the first circle (c1) is created with all values specified. The second circle (c2) is created with values for Y and R, 0 (default value for integer) will be given to X field. We use field name : (colon) field value notation to assign value to specific field. The third circle (c3) is created with no value assigned to any field. All fields will have default values for their respective types. In our case all fields are integers, so value 0 will be given to all fields.
package main
import fmt
type Circle struct {
X, Y, R int
}
func main() {
c1 := Circle{2, 3, 5}
c2 := Circle{Y: 1, R: 5}
c3 := Circle{}
fmt.Println(c1)
fmt.Println(c2)
fmt.Println(c3)
}
1.5.5 Arrays
Array is complex data type and represents collection of same type of elements. Each element is identified by array index. The first element of array will have index 0.
To declare array, in Go, we must write array length (integer value) between square brackets before type in variable declaration statement. This statement will declare integer array of five integers.
var arr [5]int
We can initialize array, after type between curly brackets we can specify values for elements of array. If we don’t initialize values, default values will be given to each element. We can use short assignment statement to declare array. This statement will create and initialize array of five integers.
arr := [5]int{4, 7, 2, 9, 1}
In Go, array length (value between square brackets) is part of array type. So when size is once defined, cannot be changed. This may