Full-Stack Web Development with Go Build your web applications quickly using the Go programming language and Vue.js 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. 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 Contributors About the authors 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). 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 Preface xi Part 1: Building a Golang Backend 1 Building the Database and Model 3 Technical requirements 4 Using sqlc 11 Installing Docker 4 Setting up the database 13 Setting up Postgres 5 Generating CRUD with sqlc 14 Designing the database 6 Building the makefile 21 Installing sqlc 9 Summary 22 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 Summary 36 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 Installing Jaeger 41 Adding metrics using Prometheus 50 Adding metrics using Prometheus 52 Integrating the Jaeger SDK 43 Integration with Jaeger 44 Running docker-compose 58 Summary 60 Part 2: Serving Web Content 4 Serving and Embedding HTML Content 63 Technical requirements 63 Rendering static content 72 Handling HTTP functions and Rendering dynamic content 74 Gorilla Mux 63 Using Go embed to bundle Hello, World with defaults 64 your content 78 Building on the basics with Gorilla Mux 67 Summary 83 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 Adding middleware 90 Summary 97 Basic middleware 90 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 Converting to and from JSON 108 Using JSONError 112 Defining request model 109 Using JSONMessage 114 Defining a response model 111 Summary 115 Reporting errors with JSON 112 Part 3: Single-Page Apps with Vue and Go 7 Frontend Frameworks 119 Technical requirements 119 Application and components 124 Server-side rendering versus single- Login page using Vue 124 page apps 119 Using Vite 127 Introducing React, Vue, and more 120 Using Vue Router to move around 130 React 120 Routing the login page 132 Svelte 121 Summary 133 Vue 121 Creating a Vue app 124 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 Summary 150 Bulma sample 140 9 Tailwind, Middleware, and CORS 151 Technical requirements 151 Introducing Tailwind 151