32,67 €
A Go programmer's hands-on guide to go from building basic server-side templates to full single page apps using Tailwind CSS, Vue.js, and more
Key Features
Book Description
Go is a modern programming language with capabilities to enable high-performance app development. With its growing web framework ecosystem, Go is a preferred choice for building complete web apps. This practical guide will enable you to take your Go skills to the next level building full stack apps.
This book walks you through creating and developing a complete modern web service from auth, middleware, server-side rendering, databases, and modern frontend frameworks and Go-powered APIs. You'll start by structuring the app and important aspects such as networking, before integrating all the different parts together to build a complete web product. Next, you'll learn how to build and ship a complete product by starting with the fundamental building blocks of creating a Go backend. You'll apply best practices for cookies, APIs, and security, and level up your skills with the fastest growing frontend framework, Vue. Once your full stack application is ready, you'll understand how to push the app to production and be prepared to serve customers and share it with the world.
By the end of this book, you'll have learned how to build and ship secure, scalable, and complete products and how to combine Golang with existing products using best practices.
What you will learn
Who this book is for
This book is for Go programmers who want to combine the power of the Go language with modern web development technologies to build complete web apps from frontend to backend. The book assumes beginner-level knowledge of HTML, CSS, and the web.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 260
Veröffentlichungsjahr: 2023
Build your web applications quickly using the Go programming language and Vue.js
Nanik Tolaram
Nick Glynn
BIRMINGHAM—MUMBAI
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.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Bhavya Rao
Senior Content Development Editor: Feza Shaikh
Technical Editor: Saurabh Kadave
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Shyam Sundar Korumilli
Marketing Coordinator: Anamika Singh
First published: February 2023
Production reference: 1270123
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
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
Nanik Tolaram is a big proponent of open source software. He has dabbled in different programming languages, such as Java, JavaScript, C, and C++. He has developed different products from the ground up while working in start-up companies. He is a software engineer at heart, but he loves to write technical articles and share his knowledge with others. He learned to program with Go during the COVID-19 pandemic and hasn’t looked back.
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).
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.
Full-Stack Web Development with Go walks you through creating and developing a complete modern web service, from authn/authz, interop, server-side rendering, and databases, to modern frontend frameworks with Tailwind and Go-powered APIs, complete with step-by-step explanations of essential concepts, practical examples, and self-assessment questions. The book will begin by looking at how to structure the app and look at the relevant pieces, such as database and security, before integrating all the different parts together to build a complete web product.
Developers with experience of a mixture of frontend and backend development will be able to put their knowledge to work with the practical guide in this book. The book will give them the know-how to glue together their skills and allow them to build a complete stack web application.
Chapter 1, Building the Database and Model, looks at building our database for our sample application. We will also explore different ways to communicate with databases using Golang.
Chapter 2, Application Logging, considers how designing an application requires examining it internally without going through reams of code, and the only way to do this is by logging. We will learn how to do this by running a centralized logger that will host all of our logging information. We will also learn how to log from inside our application.
Chapter 3, Application Metrics and Tracing, considers how having logging applied inside our application will assist in troubleshooting issues when the application is running. The other thing that helps is information about the interaction of the different components inside our application, which we will also look at in this chapter.
Chapter 4, Serving and Embedding HTML Content, sees us begin work on implementing the REST endpoints needed for our financial application. The first version of the app will show simple content rendered by the backend.
Chapter 5, Securing the Backend and Middleware, notes that we need to secure our application so that we can ensure users see only the data that they should. We will discuss some of the ways we can protect our endpoints using cookies, session management, and other types of middleware available.
Chapter 6, Moving to API - First, starts by laying the groundwork for frontend applications to consume our data. We’ll introduce marshaling/unmarshaling data into custom structures and see how to set up JSON-consuming endpoints and use cURL to verify.
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.
You will need the following installed on your computer: Node.js (version 16 or above), Docker (or Docker Desktop), the Golang compiler, and an IDE such as GoLand or VSCode.
Software/hardware covered in the book
Operating system requirements
Golang 1.16 and above
macOS, Linux, Windows (via WSL2)
Docker
macOS, Linux, Windows (via WSL2)
An IDE (VSCode or GoLand)
macOS, Linux, Windows
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.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Full-Stack-Web-Development-with-Go. If there’s an update to the code, it will be updated in the GitHub repository.
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/EO4sG.
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”)) ... }()Any command-line input or output is written as follows:
[INFO] 2021/11/26 21:11 This is an info message, with colors (if the output is terminal)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.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] 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.
Once you’ve read Full-Stack Web Development with Go, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781803234199
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn 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:
Chapter 1, Building the Database and ModelChapter 2, Application LoggingChapter 3, Application Metrics and TracingIn this chapter, we will design the database that our sample application will use. We will walk through the design of the database and look at some of the tools that we are going to use to help us on our database design journey. We will be using the Postgres database and will look at how to run it locally using Docker. What is Docker? In simple terms, Docker is a tool that allows developers to run a variety of applications such as the database, the HTTP server, system tools, and so on – locally or in the cloud. Docker removes the need to install all the different dependencies required to use a particular application such as a database, and it makes it easier to manage and maintain applications than installing on bare metal in both local and cloud environments. This is possible using Docker because it packages everything into a single file similar to how a compressed file contains different files internally.
We will learn how to design a database that supports the features that we want to build, such as the following:
Creating an exerciseCreating a workout plan Logging in to the systemWe 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 DockerSetting up PostgresDesigning the databaseInstalling sqlcUsing sqlcSetting up the databaseGenerating CRUD with sqlcBuilding the makefileIn 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.
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/.
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:
docker run --name test-postgres \ -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgresThe 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:
f7bdfb7d2c10c5f0c9227c9b0a720f21d3c7fa65907eb0c546b8f20f12621102Check 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:
docker exec -it test-postgres psql -h localhost -p 5432 -U postgres -d postgresWhat 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:
psql (12.3, server 14.5 (Debian 14.5-1.pgdg110+1)) WARNING: psql major version 12, server major version 14. Some psql features might not work. Type "help" for help. postgres=#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:
psql (12.3, server 14.0 (Debian 14.0-1.pgdg110+1)) WARNING: psql major version 12, server major version 14. Some psql features might not work. Type "help" for help. postgres=#Exit psql to go back to the command prompt by typing exit.
The following is some guidance on common errors when trying to connect to the database:
Error Message
Description
psql: error: could not connect to server: FATAL: password authentication failed for user “postgres”
The password specified when running Postgres does not match with the password passed in using psql. Check the password.
psql: error: could not connect to server: could not connect to server: Host is unreachable
The IP address that you use to connect to Postgres is wrong.
With this, you have completed the local setup of Postgres and are now ready to start looking into designing the database.
In this section, we will look at how to design the database to allow us to store information for the fitness tracking application. The following screenshot shows a mockup of the application:
Figure 1.1 – Screenshot of the sample application
Looking at these functionalities, we will look at designing a database structure that will look like the following entity relationship diagram:
Entity relationship diagram
An entity relationship diagram shows the relationships of entity sets stored in a database.
Figure 1.2 – Entity relationship diagram of our fitness application
Let’s drill further into each table to understand the data that they contain:
Table Name
Description
Users
This table contains user information for login purposes. Passwords will be stored as a hash, not plaintext.
Images
This table contains images of exercises that users want to do. This table will store all the exercise images that the user uploads.
Exercises
This table contains the name of the exercise that the user wants to do. Users will define what kind of exercise they want to do.
Sets
This table contains the number of sets of each exercise that the user wants to do.
Workouts
This table contains the workouts that the user wants to do. Users define a workout as a combination of exercises with the number of sets that they want to do.
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.
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.
Figure 1.3 – Flow to use sqlc to generate Go code
All SQL code will be written in .sql files, which will be read and converted by the sqlc tool into the different Go code.
Download and install SQL binary by using the following command:
go install github.com/kyleconroy/sqlc/cmd/sqlc@latestMake 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/binIf 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 sqlcUse "sqlc [command] --help" for more information about a command.
At the time of writing, the latest version of sqlc is v1.13.0.
Now that we have installed the tool and understand the development workflow that we will be following when using the tool, we will look at how to use the tool for our application.
First, let’s take a look at the different commands provided by sqlc and how they work.
Commands
Explanation
compile
This command helps check SQL syntax and reports any typing errors.
completion
This command is to generate an auto-completion script for your environment. The following are the supported environments: Bash, Fish, PowerShell, and zsh.
generate
A command to generate the .go files based on the provided SQL statements. This will be the command that we will be using a lot for the application.
init
This command is the first command that is used to initialize your application to start using this tool.
The following will show how to get started with using sqlc to set up a project. Create a directory inside chapter1 – for example, dbtest – and change the directory to the new directory (dbtest). Next, we will run sqlc with the init command:
sqlc initThis will automatically generate a file called sqlc.yaml, which contains a blank configuration as shown here:
version: "1" project: id: "" packages: []The sqlc.yaml contains configuration information that sqlc will use to generate all the relevant .go code for our SQL statements.
Let’s take a look at the structure of the .yaml file to understand the different properties. The following shows an example of a completed structure:
version: "1" packages: - name: "db" path: "db" queries: "./sqlquery" schema: "./sqlquery/schema/" engine: "postgresql" sql_engine: "database/sql" emit_db_tags: "true" emit_prepared_queries: true emit_interface: false emit_exact_table_names: false emit_empty_slices: false emit_exported_queries: false emit_json_tags: true json_tags_case_style: "snake" output_db_file_name: "db.go" output_models_file_name: "dbmodels.go" output_querier_file_name: "dbquerier.go" output_files_suffix: "_gen"The following table explains the different fields:
Tag Name
Description
Name
Any string to be used as the package name.
Path
Specifies the name of the directory that will host the generated .go code.
Queries
Specifies the directory name containing the SQL queries that sqlc will use to generate the .go code.
Schema
A directory containing SQL files that will be used to generate all the relevant .go files.
Engine
Specifies the database engine that will be used: sqlc supports either MySQL or Postgres.
emit_db_tags
Setting this to true will generate the struct with db tags – for example:
type ExerciseTable struct {
ExerciseID int64 `db:"exercise_id"
ExerciseName string `db:"exercise_name"
}
emit_prepared_queries
Setting this to true instructs sqlc to support prepared queries in the generated code.
emit_interface
Setting this to true will instruct sqlc to generate the querier interface.
emit_exact_table_names
Setting this to true will instruct sqlc to mirror the struct name to the table name.
emit_empty_slices
Setting this to true will instruct sqlc to return an empty slice for returning data on many sides of the table.
emit_exported_queries
Setting this to true will instruct sqlc to allow the SQL statement used in the auto-generated code to be accessed by an outside package.
emit_json_tags
Setting this to true will generate the struct with JSON tags.
json_tags_case_style
This setting can accept the following – camel, pascal, snake, and none. The case style is used for the JSON tags used in the struct. Normally, this is used with emit_json_tags.
output_db_file_name
Name used as the filename for the auto-generated database file.
output_models_file_name
Name used as the filename for the auto-generated model file.
output_querier_file_name