Web Programming with Go
By Ian Taylor
()
About this ebook
Web Programming with Go is a must-have book for software professionals and web developers looking to harness Go's potential for creating excellent web apps. The extensive knowledge imparted by this book about Go's powerful libraries and packages is crucial for building scalable and efficient web platforms.
The book's core focus is on exploring deeply into the complexities of web development through the perspective of Go. The first step in building any web application is to review the fundamentals, which will serve as a foundation for the rest of the learning experience. As you explore deeper, you'll learn about the diverse ecosystem that supports Go. This book covers a wide range of issues, including the complexities of routing mechanics, HTTP requests, and Go's concurrency model, all with the goal of improving web efficiency.
The book uses the example of a "bookstore app" throughout the book, providing you with a practical touchpoint on every possible learning. With this iterative example, you can follow the development of a simple web app from its infancy all the way to a fully featured, robust platform. The later sections of the book focus on performance evaluation and debugging, which are frequently overlooked in other Go books.
This book takes you from the fundamentals of web development to the depths of Go, culminating in a strong online application designed to meet today's digital issues. This book promises to be your compass in the vast ocean of web development, whether you're an experienced developer or an enthusiast just getting started with Go.
Key Learnings
- Master Go's efficient syntax and streamline coding with better performance.
- Build robust web applications from scratch, ensuring scalability and responsiveness.
- Seamlessly integrate APIs, enhancing app functionality and user experience.
- Harness Go's concurrency, boosting app speed and multitasking capabilities.
- Optimize data storage and retrieval with Go, ensuring data integrity and speed.
- Develop resilient apps by mastering error detection and troubleshooting in Go.
- Implement user sessions, enhancing user experience and data security.
- Ensure app reliability through Go's comprehensive testing and debugging techniques.
- Utilize Go tools for real-time performance tracking, ensuring optimal user experiences.
- Safeguard user data and interactions through Go's top-tier security practices.
Table of Content
- Introduction to Web Development in Go
- Structuring Go Web Application
- Handling HTTP Requests and Routing
- Templating and Rendering Content
- Interaction with Databases
- Concurrency in Go
- Sessions, Authentication and Authorization
- Frontend and Backend Communication
- Testing and Debugging
Read more from Ian Taylor
Mastering Go Network Automation Rating: 0 out of 5 stars0 ratingsGo Programming Cookbook Rating: 0 out of 5 stars0 ratings
Related to Web Programming with Go
Related ebooks
Coding Languages: Angular With Typescript, Machine Learning With Python And React Javascript Rating: 0 out of 5 stars0 ratingsPython Apps on Visual Studio Code: Develop apps and utilize the true potential of Visual Studio Code (English Edition) Rating: 0 out of 5 stars0 ratingsAndroid Application Development with Maven Rating: 0 out of 5 stars0 ratingsMastering Google App Engine Rating: 0 out of 5 stars0 ratingsAsynchronous Android Rating: 4 out of 5 stars4/5Python AI Programming Rating: 0 out of 5 stars0 ratingsTesting Applications on the Web: Test Planning for Internet-Based Systems Rating: 3 out of 5 stars3/5Basic Guide to Programming Languages Python, JavaScript, and Ruby Rating: 0 out of 5 stars0 ratingsJavaScript Mobile Application Development Rating: 0 out of 5 stars0 ratingsHeroku Cookbook Rating: 0 out of 5 stars0 ratingsCreating Great Android Apps: Tips and Advice Rating: 0 out of 5 stars0 ratingsVps Toolkit Rating: 0 out of 5 stars0 ratingsFull Stack JavaScript A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsJavaScript Unleashed: Harnessing the Power of Web Scripting Rating: 0 out of 5 stars0 ratingsTwilio Cookbook Rating: 0 out of 5 stars0 ratingsMission Ruby Rating: 0 out of 5 stars0 ratingsG-Code "Why We Don't Tell" Rating: 0 out of 5 stars0 ratingsPHP Programming Solutions Rating: 0 out of 5 stars0 ratingsRust for the IoT: Building Internet of Things Apps with Rust and Raspberry Pi Rating: 0 out of 5 stars0 ratingsSwift Essentials - Second Edition Rating: 0 out of 5 stars0 ratingsFundamentals of Android App Development: Android Development for Beginners to Learn Android Technology, SQLite, Firebase and Unity Rating: 0 out of 5 stars0 ratingsBootstrap for Rails Rating: 0 out of 5 stars0 ratingsProgramming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C# Rating: 0 out of 5 stars0 ratingsPython, PyGame, and Raspberry Pi Game Development Rating: 0 out of 5 stars0 ratingsNear Field Communication with Android Cookbook Rating: 0 out of 5 stars0 ratingsA World of Programming Rating: 0 out of 5 stars0 ratingsSocial Media for WordPress Beginner's Guide Rating: 0 out of 5 stars0 ratingsThe BillyGate Affair: How Hackers at Microsoft and Google Revealed Their Massive Malware Operation Rating: 0 out of 5 stars0 ratingsBasic Principles of an Operating System Rating: 0 out of 5 stars0 ratings
Internet & Web For You
The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsThe Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5Coding For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Wireless Hacking 101 Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 4 out of 5 stars4/5Six Figure Blogging In 3 Months Rating: 4 out of 5 stars4/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 5 out of 5 stars5/5Wordpress for Beginners: The Easy Step-by-Step Guide to Creating a Website with WordPress Rating: 5 out of 5 stars5/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5SEO For Dummies Rating: 4 out of 5 stars4/5Remote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5The Designer's Web Handbook: What You Need to Know to Create for the Web Rating: 0 out of 5 stars0 ratingsThe Mega Box: The Ultimate Guide to the Best Free Resources on the Internet Rating: 4 out of 5 stars4/5From Nothing Rating: 5 out of 5 stars5/5Mike Meyers' CompTIA Security+ Certification Guide, Third Edition (Exam SY0-601) Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Podcasting For Dummies Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsGet Rich or Lie Trying: Ambition and Deceit in the New Influencer Economy Rating: 0 out of 5 stars0 ratingsStop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsHow To Start A Podcast Rating: 4 out of 5 stars4/5
Reviews for Web Programming with Go
0 ratings0 reviews
Book preview
Web Programming with Go - Ian Taylor
Web Programming with Go
Building and Scaling Interactive Web Applications with Go’s Robust Ecosystem
Ian Taylor
Preface
Web Programming with Go
is a must-have book for software professionals and web developers looking to harness Go's potential for creating excellent web apps. The extensive knowledge imparted by this book about Go's powerful libraries and packages is crucial for building scalable and efficient web platforms.
The book's core focus is on exploring deeply into the complexities of web development through the perspective of Go. The first step in building any web application is to review the fundamentals, which will serve as a foundation for the rest of the learning experience. As you explore deeper, you'll learn about the diverse ecosystem that supports Go. This ecosystem covers a wide range of issues, including the complexities of routing mechanics, HTTP requests, and Go's concurrency model, all with the goal of improving web efficiency.
The book uses the example of a bookstore app
throughout the book, providing you with a practical touchpoint on every possible learning. With this iterative example, you can follow the development of a simple web app from its infancy all the way to a fully featured, robust platform.
The later sections of the book focus on performance evaluation and debugging, which are frequently overlooked in other Go books. This book takes you from the fundamentals of web development to the depths of Go, culminating in a strong online application designed to meet today's digital issues. This book promises to be your compass in the vast ocean of web development, whether you're an experienced developer or an enthusiast just getting started with Go.
In this book you will learn how to:
Master Go's efficient syntax and streamline coding with better performance.
Build robust web applications from scratch, ensuring scalability and responsiveness.
Seamlessly integrate APIs, enhancing app functionality and user experience.
Harness Go's concurrency, boosting app speed and multitasking capabilities.
Optimize data storage and retrieval with Go, ensuring data integrity and speed.
Develop resilient apps by mastering error detection and troubleshooting in Go.
Implement user sessions, enhancing user experience and data security.
Ensure app reliability through Go’s comprehensive testing and debugging techniques.
Utilize Go tools for real-time performance tracking, ensuring optimal user experiences.
Safeguard user data and interactions through Go's top-tier security practices.
Prologue
With new online technologies appearing seemingly out of nowhere, developers in this day must choose a language that can include speed, reliability, and efficiency into their work. This is where Web Programming with Go
comes in, taking you on a comprehensive journey through the huge universe of Go's web capabilities.
Go, or Golang as it is generally called, did not emerge by chance. It was a purposeful design by tech titans who saw a hole in the linguistic landscape and felt compelled to fill it with a language that was current, succinct, and innately equipped to deal with the issues of today's multithreaded online environments. Go was created with a concept in mind: to simplify the complex and emphasize the important, making it a joy for developers to choreograph programs that were not only functional, but also performative.
Web Programming with Go
is more than simply a how-to guide for functions, loops, and libraries; it's a manifesto for modern web programming. Each chapter peels back the layers of Go, guaranteeing that by the end, you have not only comprehended but also assimilated its philosophy. It is necessary to comprehend the why before the how. Why Go favors composition over inheritance, why Go's concurrency model is its finest achievement, and why Go could be the language you didn't realize you needed.
This book's underpinning strength is its hands-on methodology. We believe in learning by doing, so a constant thread of a practical example - our beloved 'bookstore app' - runs through the book's tapestry. It, like you, evolves, grows, and scales. Our bookshop software stands as a tribute to the strength of Go, moving from a primitive model into a state-of-the-art application with each chapter as we delve into subjects ranging from routing mechanics to API integrations.
The modern web is about more than just retrieving and presenting data; it's about integrating with a plethora of services, providing dynamic user experiences, scaling on the fly, and, most critically, ensuring performance doesn't deteriorate even while under strain. As you read this book, you'll notice Go standing tall, a beacon guiding you through these difficulties. You'll learn how to use Go's power to make sure your applications aren't simply useful, but also fast.
Another noteworthy aspect of this book is its in-depth examination of debugging and performance evaluation. Debugging is more than just finding mistakes; it's about understanding your application, identifying its pain points, and addressing them. Go's vast toolkit makes this once-difficult operation practically intuitive, and this book assures you're well-prepared to employ every tool in Go's arsenal.
We hope you find Web Programming with Go
not only instructive but also transforming as you embark on this adventure. Whether you're a seasoned coder, an enthusiast, or someone at a crossroads of languages unsure which path to choose, this book aims to be your compass, guide, and, at times, mentor. As you turn the page, you're not just beginning a new chapter; you're embarking on what we promise will be an exciting journey into the world of Go. Have fun coding!
Copyright © 2023 by GitforGits
All rights reserved. This book is protected under copyright laws and no part of it may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without the prior written permission of the publisher. Any unauthorized reproduction, distribution, or transmission of this work may result in civil and criminal penalties and will be dealt with in the respective jurisdiction at anywhere in India, in accordance with the applicable copyright laws.
Published by: GitforGits
Publisher: Sonal Dhandre
www.gitforgits.com
support@gitforgits.com
Printed in India
First Printing: October 2023
ISBN: 9788119177943
Cover Design by: Kitten Publishing
For permission to use material from this book, please contact GitforGits at support@gitforgits.com.
Content
Preface
Chapter 1: Introduction to Web Development in Go
Introduction to Web Development
Opportunities for Go
Go Toolchain
Compiler
Dependency and Package Management
Testing and Benchmarking
Setting up Go on Linux
Installing Go
Configuring Go Workspace
Introducing Go Modules
Setting up Tools and Libraries
IDE and Code Editors
net/http Package
net/http Overview
HTTP Servers and Clients
Handlers and HandlerFuncs
Routing Requests
Data Request and Response
Using net/http
Introducing Bookstore Web Application
Go RESTful Services
Key Principles of REST
Implementing RESTful Services with Go
Go's Advantage in RESTful Development
Building my First Web Server
Initializing Project
Crafting Basic Server
Running the Server
Summary
Chapter 2: Structuring Go Web Application
Explore Go Modules
Essence of Go Modules
Transitioning to Modules
Dependency Management with Modules
Understanding Module Proxies
Standard Go Directory Structure
Designing Directory Structure
Package Management and Vendoring
Why Package Management Matters?
Need of Vendoring
Implementing Package Management
Model-View-Controller (MVC) in Go
Understanding MVC
Benefits of MVC
Applying MVC to GitforGits Bookstore
Programming Main Application Object
Defining Application Object Structure
Crafting Main Application Object
Decoding the Script
Configuration and Environment Variables
Implementing Configuration and Environment Variables
Dependency Injection
Overview
Benefits of Dependency Injection
Implementing Dependency Injection
Health Check Endpoints
Setting up Health Check Endpoints
Summary
Chapter 3: Handling HTTP Requests and Routing
Backbone of Web
HTTP Requests and Routing
HTTP Methods
Navigate User Interactions
Request-Response Paradigm
Request Phase
Response Phase
Handlers and HandlerFuncs
Understanding HandlerFuncs
Explore Routes
Routes as Connectors
Route Patterns and Dynamic Routing
Route Grouping and Hierarchical Routing
Routes Programming
Setting up Routes
Dynamic Routes and Route Variables
Middleware in Routing
Error Handling and Custom 404 Pages
URL Parameters
Types of URL Parameters
Implementing Dynamic URL Parameters
Grouping Routes
Overview
Sample Program: Structuring Endpoints
Navigate Web Routing with Gorilla/Mux
Setting up Gorilla/Mux
Configuring Gorilla/Mux for Optimal Performance
Error Handling in Go
404 Not Found Error
500 Internal Server Error
Rate Limiting and Request Throttling
Overview
Rate Limiting for GitforGits Bookstore
Performing CRUD Operations
Creating Book
Reading Book Details
Updating Book
Deleting Book
Summary
Chapter 4: Templating and Rendering Content
Dynamic Rendering Overview
Templates Deep Dive
Symphony of Variables
Loops
Conditions
Nested Templates in Action
Constructing the Framework
Carving the Header
Crafting the Content
Sealing the Footer
Design Main Page Layout
Structuring Base Layout
Designing Header
Building Dynamic Content Area
Outlining Holistic Footer
Handling Forms and User Inputs
Laying Groundwork
Dropdowns, Radios, and Checkboxes
Validation
Processing Form Data
Template Caching
Overview
Go's Template Package
Deploying Cached Templates
Safe HTML Rendering
Need for Safe Rendering
Cross-Site Scripting (XSS)
Contextual Encoding
Template Debugging
Scenario#1: Malformed Templates
Scenario#2: Missing or Mismatched Data
Scenario#3: Incorrect Logic or Conditions
Summary
Chapter 5: Interaction with Databases
Introduction to Persistent Storage
database/sql Package
Overview
Install Drivers
Connecting Database
Crafting and Executing Queries
Insertions, Updates, and Deletions
Managing Database Connections
Sample Program: Design Robust Database
Nature of Data
Books as Core Entity
Categorizing Books as Genres
Users
Book Reviews
Transactions
Inventory Management
Leverage ORMs
Strengthen Database Indexing
Primary Indexing
Secondary Indexing
Primary vs. Secondary Indexes
Composite Indexes
Covering Indexes
Partial Indexes
Manage Database Connections
Connection Pooling
Integrating Connection Pooling
Tuning Connection Pool
Connection Health Checks
Advanced SQL Queries
Joins
Subqueries
Aggregations
Summary
Chapter 6: Concurrency in Go
Age of Rapid Applications
Concurrency for Parallel Execution
Go's Concurrency Paradigm
Go’s Goroutines
Understanding Goroutines
Sample Program: Concurrent Book Searches
Goroutines Channeling
Need of Channels
Using Channels
Buffered Channels
Closing Channels
Multiplexing Channel Operations
Up and Running with Synchronization
Importance of Synchronization
sync.WaitGroup
sync.Mutex
Combining WaitGroup and Mutex
Implement Concurrent Cache
Parallelism vs. Concurrency
Unveiling Parallelism
Sample Program: Book Recommendation Function
Do's and Don'ts
Summary
Chapter 7: Sessions, Authentication, and Authorization
User Sessions Overview
Store Session Data
Session Storage Options
Secure Cookie Handling
Secure Cookies Overview
Implementing HTTPOnly Attribute
Secure Cookies with Secure Attribute
SameSite Attribute
Encrypting Cookie Values
Implement User Authentication
Setting up Database
Registering New User
Logging In an Existing User
Managing User Sessions
Logging Out User
Protect and Secure User Passwords
Hashing
Salting
Pepper
Iterations
Up-to-date Algorithms
Implement and Operate OAuth
Understanding OAuth
Setting up OAuth
Redirection and Callbacks
Summary
Chapter 8: Frontend and Backend Communication
Frontend-Backend Overview
RESTful API Overview
Background
Stateless Interactions
Client-Server Architecture
Uniform Interface
Layered System
State Representations
Build My First API
Project Initialization and Import Packages
Defining Book Structure
Sample Data
Creating Endpoint Function
Setting up Server
Testing Endpoint
JSON and Its Importance
Basic JSON Structure
Program Data Fetching
Setting up Endpoint
Interacting with Database
Goroutines and Channels for Data Fetching
Why Concurrency in Data Fetching?
Sample Program: Concurrent Data Fetching
Authenticating APIs
Importance of API Security
What is API Authentication?
Using API Tokens for Authentication
Generating and Validating Tokens
Middleware for Authentication
Integrate External APIs
Choose and Communicate Third-Party API
Sample Program: Integration of Payment Gateway
Summary
Chapter 9: Testing and Debugging
Testing and Debugging Overview
Go Testing Package
Fundamentals
Powerful Assertions and Flow Control
Performance Benchmarks
Testing Web Applications
Initiating Testing
Setting up Environment
Test File Structure
Fetching a Book
Executing Test
Refining Test with Mock Data
Enhancing Test
Handling Multiple Test Cases
Table-Driven Testing
Utilizing Helper Functions
Parallel Testing
Subtests
Mock Dependencies
Introduction to Mocking
Why Mock Dependencies?
Creating Mock Database
Using Mock in Tests
Tracing and Logging
Performing Logging with Go's log
Integrating Advanced Logging Libraries
Error Tracing
Application Performance Profiling
CPU Profiling
Block Profiling
Memory Profiling
Errors and Troubleshooting
N+1 Query Problem
Data Race Conditions
Memory Leaks
Broken Authentication Flows
Inefficient Data Handling
Input Validation Failures
Incorrect Error Handling
Dependency Update Failure
Hardcoding Configuration
Unsafe Concurrency Handling
Summary
Index
Epilogue
GitforGits
Prerequisites
Targeted at experienced programmers in other languages and Go beginners interested in mastering web application development, and professionals seeking to update their web development toolkit with Go.
Codes Usage
Are you in need of some helpful code examples to assist you in your programming and documentation? Look no further! Our book offers a wealth of supplemental material, including code examples and exercises.
Not only is this book here to aid you in getting your job done, but you have our permission to use the example code in your programs and documentation. However, please note that if you are reproducing a significant portion of the code, we do require you to contact us for permission.
But don't worry, using several chunks of code from this book in your program or answering a question by citing our book and quoting example code does not require permission. But if you do choose to give credit, an attribution typically includes the title, author, publisher, and ISBN. For example, Web Programming with Go by Ian Taylor
.
If you are unsure whether your intended use of the code examples falls under fair use or the permissions outlined above, please do not hesitate to reach out to us at support@gitforgits.com.
We are happy to assist and clarify any concerns.
Chapter 1: Introduction to Web Development in Go
Introduction to Web Development
In 2007, Robert Griesemer, Rob Pike, and Ken Thompson at Google came up with the idea for the Go programming language, which is also referred to as Golang. Their intention was to address the complexities and deficiencies that they saw in other languages. What began as an exploratory project with the intention of resolving common criticisms of popular languages such as C++ and Java, particularly in terms of scalability and concurrency, eventually resulted in the release of Go 1.0 in the year 2012. Not only was this a watershed moment in the history of the language,