Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram instant download
Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram instant download
https://textbookfull.com/product/let-s-go-learn-to-build-
professional-web-applications-with-go-alex-edwards/
https://textbookfull.com/product/let-s-go-learn-to-build-
professional-web-applications-with-go-alex-edwards-2/
https://textbookfull.com/product/go-web-programming-1st-edition-
sau-sheong-chang/
Mastering Full Stack React Web Development 1st Edition
Tomasz Dyl
https://textbookfull.com/product/mastering-full-stack-react-web-
development-1st-edition-tomasz-dyl/
https://textbookfull.com/product/pro-mern-stack-full-stack-web-
app-development-with-mongo-express-react-and-node-vasan-
subramanian/
https://textbookfull.com/product/essential-asp-net-web-forms-
development-full-stack-programming-with-c-sql-ajax-and-
javascript-1st-edition-robert-e-beasley/
https://textbookfull.com/product/pro-mern-stack-full-stack-web-
app-development-with-mongo-express-react-and-node-2nd-edition-
vasan-subramanian/
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
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