Download Full Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram PDF All Chapters
Download Full Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram PDF All Chapters
com
https://textbookfull.com/product/full-stack-web-development-
with-go-build-your-web-applications-quickly-using-the-go-
programming-language-and-vue-js-1st-edition-nanik-tolaram/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/let-s-go-learn-to-build-professional-
web-applications-with-go-alex-edwards/
textboxfull.com
https://textbookfull.com/product/let-s-go-learn-to-build-professional-
web-applications-with-go-alex-edwards-2/
textboxfull.com
https://textbookfull.com/product/go-web-programming-1st-edition-sau-
sheong-chang/
textboxfull.com
Mastering Full Stack React Web Development 1st Edition
Tomasz Dyl
https://textbookfull.com/product/mastering-full-stack-react-web-
development-1st-edition-tomasz-dyl/
textboxfull.com
Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node Vasan Subramanian
https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-vasan-subramanian/
textboxfull.com
Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node 2nd Edition Vasan Subramanian
https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-2nd-edition-vasan-
subramanian/
textboxfull.com
Full-Stack Web Development
with Go
Nanik Tolaram
Nick Glynn
BIRMINGHAM—MUMBAI
Full-Stack Web Development with Go
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the case
of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable
for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.
ISBN 978-1-80323-419-9
www.packtpub.com
To my dearest Mum, who always supported me in pursuing my dreams and encouraged me to keep on
going no matter what life brought.
To my late Dad, who stood by me and encouraged me to write my very first book when I was
17 years old.
To my beautiful wife and best friend, for allowing me the time to write the book and supporting me in
every step of our life.
To both my sons, Rahul and Manav, for allowing me to spend time in front of the computer on
weekends to chase my dream and passion. Last but not least, to God, for giving me this life and the
opportunity to be where I am in this world.
– Nanik Tolaram
I would like to thank my family for their love; my beautiful daughter Inara, for always being there
to brighten my day; and my beautiful partner Kate, for all her support in my business efforts and in
writing this book.
– Nick Glynn
Contributors
I want to thank the Packt team – Feza Shaikh, Bhavya Rao, Manthan Patel, and Mark D’Souza – for
their guidance and patience in helping us complete the book.
Nick Glynn is the founder and current chief product officer of FeeWise, a US payments and finance
platform.
He has previously worked in CTO, senior, and principal engineering roles developing products, training,
and consulting for companies such as Intel, Qualcomm, Hewlett Packard, L3, and many more.
With a broad range of experience from board bring-up, Linux driver development, and systems
development up through to building and deploying platforms that power investment and financial
institutions, Nick is always looking to build pragmatic solutions to real-world problems.
Nick also continues his independent efforts as a trainer and consultant, delivering courses and expertise
globally through his company Curiola (www.curiola.com).
About the reviewers
Pablo David Garaguso was born in Mar del Plata, Argentina. He graduated with two degrees in
computer sciences and enterprise systems from CAECE University and later on received an MBA
from CEMA University in Buenos Aires, Argentina. He has worked as an attached professor, project
leader, and international manager, and currently occupies a position as a solutions architect in R&D
for FamilySearch Int. Europe. Based in Finland, he has published a variety of books according to his
many interests, from novels and fiction to software engineering. His latest book, Vue 3 Applications
and Design Patterns, will be published by Packt in 2023.
Suraj Bobade is an experienced software professional, currently located in Pune, India. He completed
a B.Tech in computer science from Walchand College of Engineering, Sangli.
He is passionate about software development with a keen interest in product management. He builds
user-first feature-rich products while driving critical software and product design decisions.
Go has been his go-to choice for building the microservice backend and prototypes. Considering the
simplicity and increasing adoption by the open source community, Suraj is optimistic that readers of
this book will learn in-demand skills.
Tan Quach is an experienced software engineer with a career spanning over 25 years and exotic locations
such as London, Canada, Bermuda, and Spain. He has worked with a wide variety of languages and
technologies for companies such as Deutsche Bank, Merrill Lynch, and Progress Software, and loves
diving deep into experimenting with new ones.
Tan’s first foray into Go began in 2017 with a proof-of-concept application built over a weekend and
productionized and released 3 weeks later. Since then, Go has been his language of choice when
starting any project.
When he can be torn away from the keyboard, Tan enjoys cooking meat over hot coals and open
flames and making his own charcuterie.
Nima Yahyazadeh is a Software Architect focused on developing solutions for startups. He has years
of experience developing distributed and cloud-native solutions. He has worked at medium to large
corporations such as Amazon Web Services, Intel, and Appian. He is currently the founder and CEO
of a consulting company, Lenzo LLC, that has helped more than five startups to architect, develop, and
deliver exciting features to their customers. He is passionate about AWS, Kubernetes, Elasticsearch,
Kafka, and Golang.
Table of Contents
Prefacexi
2
Application Logging 23
Technical requirements 23 Writing log messages to the
Exploring Go standard logging 23 logging server 30
Using golog 26 Configuring multiple outputs 33
Local logging 29 Summary36
3
Application Metrics and Tracing 37
Technical requirements 37 The OpenTelemetry APIs and SDK 39
Understanding OpenTelemetry 38 Tracing applications 40
viii Table of Contents
5
Securing the Backend and Middleware 85
Technical requirements 85 Adding cookies and sessions 92
Adding authentication 86 Cookies and session handling 92
Creating our dummy user 88 Storing session information 95
Authenticating a user 89 Using Redis for a session 95
6
Moving to API-First 99
Technical requirements 99 Exposing our REST API 102
Structuring an application 100 Cross-Origin Resource Sharing (CORS) 104
Defining packages 100 JSON middleware 105
Session middleware 107
Table of Contents ix
8
Frontend Libraries 135
Technical requirements 135 Setting up Buefy 141
Understanding Vuetify 136 UI components 142
Setting up Vuetify 136 Validating data entry with Vuelidate 143
Using UI components 137 Better input handling with Cleave.JS 148
Understanding Buefy 139 Summary150
Bulma sample 140
9
Tailwind, Middleware, and CORS 151
Technical requirements 151 Introducing Tailwind 151
x Table of Contents
Creating a new Tailwind and Vite project 153 CORS for secure applications 163
Consuming your Golang APIs 156 Creating Vue middleware 166
Summary168
10
Session Management 169
Technical requirements 169 Navigation guards 179
Session management and JWTs 169 Defaults and error pages 182
What’s a JWT? 170 Summary182
(Re)introducing Vue Router 178
12
Building Continuous Integration 199
Technical requirements 199 Dockerfile210
Importance of CI 200 GitHub Packages 210
Setting up GitHub 200 Publishing to GitHub Packages 212
GitHub Actions 204 Pulling from GitHub Packages 216
13
Dockerizing an Application 219
Technical requirements 219 Running images as containers 227
Installing Docker 219 Building and packaging images 229
Using Docker 221 Docker Compose 233
Docker images 222 Summary235
14
Cloud Deployment 237
Technical requirements 237 The init command 245
AWS refresher 238 The plan command 247
The destroy command 250
Amazon Elastic Compute Cloud 239
Virtual Private Cloud 240 Coding in Terraform 252
Database storage 241 Providers252
Elastic Container Service 242
AWS tools 242
Terraform examples 254
Pulling from GitHub Packages 255
Understanding and using Terraform 243 AWS EC2 setup 257
What is Terraform? 244 Deploying to ECS with a load balancer 261
Installing Terraform 244
Summary269
Terraform basic commands 245
Index271
Chapter 7, Frontend Frameworks, discusses the state of web development, introduces the React and
Vue frameworks, and sees us employ them to create a simple app that's similar to our previous one.
Chapter 8, Frontend Libraries, examines how to leverage tools and libraries to help us, as full stack
developers, work fast!
Chapter 9, Tailwind, Middleware, and CORS, has us securing our app and getting it talking to our
Go-powered backend.
Chapter 10, Session Management, focuses on session management while introducing state management
with Vuex and how to structure apps based on user permissions.
Chapter 11, Feature Flags, introduces feature flags (sometimes called feature toggles) as a technique
deployed to enable/disable certain features of the application as required, depending on a given
condition. For example, if a newly deployed application containing a new feature has a bug and we
know it will take time for the bug to be fixed, the decision can be made to turn off the feature without
deploying any new code to do so.
Chapter 12, Building Continuous Integration, notes that while building applications is a big part of the
puzzle, we need to be sure that what the team builds can be validated and tested properly. This is where
continuous integration comes in. Having a proper continuous integration process is super important
to ensure that everything deployed to production has been tested, verified, and checked securely.
Chapter 13, Dockerizing an Application, notes that while developing an application is one side of the coin,
the other side is to make sure that it can be deployed and used by our end user. To make deployment
simpler, we can package applications such that they can be run inside a container. Operationally, this
allows applications to be deployed in the cloud from anywhere.
Chapter 14, Cloud Deployment, shows how deploying applications to a cloud environment is the last
step in delivering features for the end user to use. Cloud deployment is complex and sometimes quite
specific to particular cloud vendors. In this chapter, we will focus on deploying applications into the
AWS cloud infrastructure.
If you are using the digital version of this book, we advise you to type the code yourself or access
the code from the book’s GitHub repository (a link is available in the next section). Doing so will
help you avoid any potential errors related to the copying and pasting of code.
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We call
next.ServerHTTP(http.ResponseWriter, *http.Request) to continue and indicate
successful handling of a request.”
A block of code is set as follows:
go func() {
...
s.SetAttributes(attribute.String(“sleep”, “done”))
s.SetAttributes(attribute.String(“go func”, “1”))
...
}()
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in
menus or dialog boxes appear in bold. Here is an example: “You will get a Login unsuccessful message.”
xvi Preface
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you have found a mistake in this book, we would be grateful if you would report this to us. Please
visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would
be grateful if you would provide us with the location address or website name. Please contact us at
[email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you
are interested in either writing or contributing to a book, please visit authors.packtpub.com.
https://packt.link/free-ebook/9781803234199
In Part 1, we will build the backend components for our sample application. We will build the database
with the models for the Go backend of our application. We will also build secure REST API endpoints
that will have logging and tracing functionalities.
This part includes the following chapters:
• Creating an exercise
• Creating a workout plan
• Logging in to the system
We will also explore tools that will help in automatic code generation based on SQL queries, which reduces
the amount of database-related code that needs to be written to a large extent. Readers will learn to use
the tool to also auto-generate all the relevant CRUD operations without writing a single line of Go code.
In this chapter, we’ll be covering the following:
• Installing Docker
• Setting up Postgres
• Designing the database
4 Building the Database and Model
• Installing sqlc
• Using sqlc
• Setting up the database
• Generating CRUD with sqlc
• Building the makefile
Technical requirements
In this book, we will be using version 1.16 of the Go programming language, but you are free to use
later versions of Go, as the code will work without any changes. To make it easy, all the relevant files
explained in this chapter can be checked out at https://github.com/PacktPublishing/
Full-Stack-Web-Development-with-Go/tree/main/Chapter01. To work on the
sample code in this chapter, make sure you change the directory to Chapter 1 – Full-Stack-
Web-Development-with-Go/chapter1. If you are using Windows as a development machine,
use WSL2 to perform all the different operations explained in this chapter.
Installing Docker
In this book, we will be using Docker to do things such as running databases and executing database
tools, among others. You can install either Docker Desktop or Docker Engine. To understand more
about the difference between Docker Desktop and Engine, visit the following link: https://
docs.docker.com/desktop/linux/install/#differences-between-docker-
desktop-for-linux-and-docker-engine. The authors use Docker Engine in Linux and
Docker Desktop for Mac.
If you are installing Docker Desktop on your local machine, the following are the links for the different
operating systems:
• Windows – https://docs.docker.com/desktop/windows/install/
• Linux – https://docs.docker.com/desktop/linux/install/
• macOS – https://docs.docker.com/desktop/mac/install/
If you want to install Docker binaries, you can follow the following guide: https://docs.docker.
com/engine/install/binaries/.
Setting up Postgres 5
Setting up Postgres
The database we chose for the sample application is Postgres; we chose Postgres over other databases
because of the wide variety of open source tools available for building, configuring, and maintaining
Postgres. Postgres has been open source from version 1 since 1989 and it is used by big tech startups
worldwide. The project has a lot of community support in terms of tools and utilities, which makes it
easier to manage and maintain. The database is suitable for small all the way to big replicated data stores.
The easiest way to run it locally is to run it as a Docker container. First, use the following command
to run Postgres:
The command will run postgres on port 5432; if by any chance you have other applications or
other Postgres instances listening to this port, the command will fail. If you need to run Postgres on a
different port, change the -p parameter (for example, -p 5555:5432) to a different port number.
If successful, you will see the container ID printed out. The ID will differ from what is shown here:
f7bdfb7d2c10c5f0c9227c9b0a720f21d3c7fa65907eb-
0c546b8f20f12621102
Check whether Postgres is up and running by using docker ps. The next thing to do is use the
psql-client tool to connect to Postgres to test it out. A list of the different Postgres client tools
available on different platforms can be found here: https://wiki.postgresql.org/wiki/
PostgreSQL_Clients.
We will use the standard postgres psql tool using Docker. Open another terminal and use the
following Docker command to run psql:
What we are doing is executing the psql command inside the running Postgres container. You will
see output such as the following, indicating that it has successfully connected to the Postgres database:
postgres=#
6 Building the Database and Model
On a successful connection, you will see the following output. Note that the warning message mentions
server major version 14 – this is to indicate that the server version is newer than the current psql
version as per the documentation (https://www.postgresql.org/docs/12/app-psql.
html). The psql client will work without any problem with the Postgres server:
With this, you have completed the local setup of Postgres and are now ready to start looking into
designing the database.
Looking at these functionalities, we will look at designing a database structure that will look like the
following entity relationship diagram:
Let’s drill further into each table to understand the data that they contain:
The trade-off we are making to store images in the database is to simplify the design; in reality, this
might not be suitable for bigger images and production. Now that we have defined the database
structure and understand what kind of data it will store, we need to look at how to implement it. One
of the major criteria that we want to focus on is to completely separate writing SQL from the code;
this way, we have a clear separation between the two, which will allow higher maintainability.
Installing sqlc
We have defined the database structure so now it’s time to talk a bit more about the tool that we are
going to be using called sqlc. sqlc is an open source tool that generates type-safe code from SQL; this
allows developers to focus on writing SQL and leave the Go code to sqlc. This reduces the development
time, as sqlc takes care of the mundane coding of queries and types.
The tool is available at https://github.com/kyleconroy/sqlc. The tool helps developers
focus on writing the SQL code that is needed for the application and it will generate all the relevant code
needed for the application. This way, developers will be using pure Go code for database operations.
The separation is clean and easily trackable.
The following diagram shows the flow that developers normally adopt when using the tool at a high level.
All SQL code will be written in .sql files, which will be read and converted by the sqlc tool into the
different Go code.
10 Building the Database and Model
go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
Make sure your path includes the GOPATH/bin directory – for example, in our case, our path looks
like the following:
…:/snap/bin:/home/nanik/goroot/go1.16.15/go/bin:/home/nanik/go/
bin
If you don’t have GOPATH as part of the PATH environment variable, then you can use the following
command to run sqlc:
$GOPATH/bin/sqlc
Usage:
sqlc [command]
Available Commands:
compile Statically check SQL for syntax and type
errors
completion Generate the autocompletion script for the
specified shell
generate Generate Go code from SQL
help Help about any command
init Create an empty sqlc.yaml settings file
upload Upload the schema, queries, and configuration
for this project
version Print the sqlc version number
Flags:
-x, --experimental enable experimental features (default:
false)
-f, --file string specify an alternate config file
(default: sqlc.yaml)
-h, --help help for sqlc
AND and OR gates in series. Switches 1 and 2, plus 3 or 4, are needed to light the
bulb.
Original Negation
A Ā
1 0
0 1
The negation device used in computer circuitry is called an inverter,
since it changes its input from a 1 to a 0, or vice versa. The
usefulness of such an element is obvious when we remember the
computer trick of subtracting by adding complements. The inverter
circuit used with a code like the excess-3 readily forms these
complements.
Further sophistication of the basic Boolean forms leads to units
other than the AND and OR gates. Possible are NOT, NOR, and
exclusive-OR forms. In the latter, there is an output if one and only
one input is present. The NOR circuit is interesting in that it was
made possible with the introduction of the transistor; the vacuum
tube does not permit this configuration.
Computer Control Co.
Electronic computers are built up of many “building blocks” like this one.
“Luckily I brought along a ‘loaner’ for you to use while I repair your computer.”
“Whatever that be which thinks, understands, wills, and
acts, it is something celestial and divine.”
—Cicero
6: The Electronic Brain
If your head starts to swim, you are not alone. Very few humans
solve such problems easily. Interestingly, those who do, make good
computer programmers.
The Computer’s Brain
Just as we have an anthropomorphic God, many people have done
their best to endow the computer with human characteristics. Not
only in fiction but also in real life, the electronic brains have been
described as neurotic and frustrated on occasion, and also as being
afraid and even having morning sickness! A salesman for a line of
computers was asked to explain in understandable terms the
difference between two computers whose specifications confused a
customer. “Let’s put it this way,” the salesman said, “The 740 thinks
the 690 is a moron!”
We can begin to investigate the question of computer intelligence
by again looking up a definition. The word “compute” means literally
to think, or reckon, with. Early computers such as counting sticks,
the abacus, and the adding machine are obviously something man
thinks with. Even though we may know the multiplication tables, we
find it easier and safer to use a mechanical device to remember and
even to perform operations for us.
These homely devices do not possess sufficient “intelligence” to
raise any fears in our minds. The abacus, for example, displays only
what we might charitably call the property of memory. It has a
certain number of rows, each row with a fixed number of beads.
While it is not fallible, as is the human who uses it, it is far more
limited in scope. All it can ever do is help us to add or subtract, and
if we are clever, to multiply, divide, do square roots, and so on. If we
are looking for purposive behavior in computing machines, it is only
when we get to the adding machine that a glimmer appears. When a
problem is set in and the proper button pushed, this device is
compelled to go through the gear-whirring or whatever required to
return it to a state of equilibrium with its problem solved.
So far we might facetiously describe the difference in the goal-
seeking characteristics of man and machine by recalling that man
seeks lofty goals like climbing mountains simply because they are
there, while the computer seeks its goal much like the steel ball in
the pinball machine, impelled by gravity and the built-in springs and
chutes of the device. When we come to a more advanced computer,
however, we begin to have difficulty in assessing characteristics. For
the JOHNNIAC, built by Rand and named for John von Neumann,
can prove the propositions in the Principia Mathematica of
Whitehead and Russell. It can also “learn” to play a mediocre game
of chess.
If we investigate the workings of a digital computer, we find much
to remind us of the human brain. First is the obvious similarity of on-
off, yes-no operation. This implies a power source, usually electrical,
and a number of two-position switches. The over-all configuration of
the classic computer resembles, in principal if not physical
appearance, that of the human brain and its accessories.
As we have learned, the electronic computer has an input section,
a control, an arithmetic (or logic) section, a memory, and an output.
Looking into the arithmetic and memory sections, we find a number
of comparisons with the brain. The computer uses power, far more
than the brain. A single transistor, which forms only part of a neuron,
may use a tenth of a watt; the brain is ahead on this score by a
factor of millions to one.
Electronic switches have an advantage over the neuron in that
they are much faster acting. So fast have they become that
engineers have had to coin new terms like nanosecond and
picosecond, for a billionth and a trillionth of a second. Thus, the
computer’s individual elements are perhaps 100,000 times faster
than those of the brain.
There is no computer in existence with the equivalent of 10 billion
neurons. One ambitious system of computers does use half a million
transistors, plus many other parts, but even these relatively few
would not fit under a size 7-1/2 hat. One advanced technique, using
a “2-D” metal film circuitry immersed in liquid helium for
supercooling, hopefully will yield a packaging density of about 3-1/2
million parts per cubic foot in comparison with the brain’s trillion-part
density.
We have mentioned the computer memory that included the
“delay line,” remindful of the “chain circuit” in the brain. Electrical
impulses were converted to acoustic signals in mercury, traversed
the mercury, and were reconverted to electrical impulses. Early
memory storage systems were “serial” in nature, like those stored on
a tape reel. To find one bit of information required searching the
whole reel. Now random-access methods are being used with
memory core storage systems so wired that any one bit of
information can be reached in about the same amount of time. This
magnetic core memory stores information as a magnetic field, again
analogous to a memory theory for the human brain except that the
neuron is thought to undergo a chemical rather than magnetic
change.
General Electric Co., Computer Dept.
Tiny ferrite cores like these make up the memory of some computers. Each core
stores one “bit” of information.
Electronics
Simplified version of a mammalian visual system (A) and Perceptron simulating the
biological network (B).
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com