Quick tip: Implementing an in-memory cache in Go

In almost all web applications that I build, I end up needing to persist some data – either for a short period of time (such as caching the result of an expensive database query), or for the lifetime of the running application until it is restarted. When your application is a sin … | Continue reading


@alexedwards.net | 5 months ago

Demystifying function parameters in Go

In this post we're going to talk about how (and why!) different types of function parameters behave differently in Go. If you're new (or even not-so-new) to Go, this can be a common source of confusion and questions. Why do functions generally mutate maps and slices, but not oth … | Continue reading


@alexedwards.net | 6 months ago

Quick tip: A time-saving Makefile for your Go projects

Whenever I start a new Go project, one of the first things I do is create a Makefile in the root of my project directory. This Makefile serves two purposes. The first is to automate common admin tasks (like running tests, checking for vulnerabilities, pushing changes to a remote … | Continue reading


@alexedwards.net | 1 year ago

How to use the http.ResponseController type

One of my favorite things about the recent Go 1.20 release is the new http.ResponseController type, which brings with it three nice benefits: You can now override your server-wide read and write deadlines on a per request basis. The pattern for using the http.Flusher and http.Hi … | Continue reading


@alexedwards.net | 1 year ago

An Introduction to Packages, Imports and Modules in Go

This tutorial is written for anyone who is new to Go. In it we'll explain what packages, import statements and modules are in Go, how they work and relate to each other and — hopefully — clear up any questions that you have. We'll start at a high level, then work down to the deta … | Continue reading


@alexedwards.net | 1 year ago

A Complete Guide to Working with Cookies in Go

Continue reading


@alexedwards.net | 1 year ago

The ‘fat service’ pattern for Go web applications

In this post I'd like to talk about one of my favorite architectural patterns for building web applications and APIs in Go. It's kind of a mix between the service object and fat model patterns — so I mentally refer to it as the 'fat service' pattern, but it might have a more form … | Continue reading


@alexedwards.net | 1 year ago

Flow: A delightfully tiny but powerful HTTP router for Go

Last year I wrote a new HTTP router for Go called Flow. I've been using it in production on this site and in a couple of other projects since, and I'm pretty happy with how it's working out so decided to share it a bit more widely. My aim with Flow was to bring together my favour … | Continue reading


@alexedwards.net | 1 year ago

Quick tip: Easy test assertions with Go generics

Now that Go 1.18 has been released with support for generics, it's easier than ever to create helper functions for your test assertions. Using helpers for your test assertions can help to: Make your test functions clean and clear; Keep test failure messages consistent; And … | Continue reading


@alexedwards.net | 2 years ago

Continuous Integration with Go and GitHub Actions

How to use GitHub Actions to create a continuous integration (CI) pipeline that automatically tests, vets and lints your Go code. | Continue reading


@alexedwards.net | 2 years ago

Quick tip: Change URL query params in Go

In this short post we're going to discuss how to add, modify or delete URL query string parameters in Go. To illustrate, we'll look at how to change this URL: https://example.com?name=alice&age=28&gender=female To this: https://example.com?name=alice&age=29&occupation=carpente … | Continue reading


@alexedwards.net | 2 years ago

Which Go router should I use? (with flowchart)

Continue reading


@alexedwards.net | 2 years ago

I18n in Go: Managing Translations

Recently I've been building a fully internationalized (i18n) and localized (l10n) web application for the first time with Go's golang.org/x/text packages. I've found that the packages and tools that live under golang.org/x/text are really effective and well designed, although it' … | Continue reading


@alexedwards.net | 2 years ago

How to correctly use Basic Authentication in Go

When searching for examples of HTTP basic authentication with Go, every result I could find unfortunately contained code which is either out-of-date (i.e. doesn't use the r.BasicAuth() functionality that was introduced in Go 1.4) or doesn't protect against timing attacks. So in t … | Continue reading


@alexedwards.net | 2 years ago

Custom command-line flags with flag.Func

One of my favorite things about the recent Go 1.16 release is a small — but very welcome — addition to the flag package: the flag.Func() function. This makes it much easier to define and use custom command-line flags in your application. For example, if you want to parse a flag l … | Continue reading


@alexedwards.net | 3 years ago

Surprises and Gotchas When Working with JSON

Continue reading


@alexedwards.net | 3 years ago

How to Manage Database Timeouts and Cancellations in Go

One of the great features of Go's database/sql package is that it's possible to cancel database queries while they are still running via a context.Context instance. On the face of it, usage of this functionality is quite straightforward (here's a basic example). But once you star … | Continue reading


@alexedwards.net | 4 years ago

How to Parse a JSON Request Body in Go

Let's say that you're building a JSON API with Go. And in some of the handlers — probably as part of a POST or PUT request — you want to read a JSON object from the request body and assign it to a struct in your code. After a bit of research, there's a good chance that you'll end … | Continue reading


@alexedwards.net | 4 years ago

Go Interfaces Explained

Continue reading


@alexedwards.net | 4 years ago

Using PostgreSQL JSONB with Go

PostgreSQL provides two JSON-related data types that you can use — JSON and JSONB. The principal differences are: JSON stores an exact copy of the JSON input. JSONB stores a binary representation of the JSON input. This makes it slower to insert but faster to query. It may chang … | Continue reading


@alexedwards.net | 5 years ago

An Overview of Go's Tooling

Continue reading


@alexedwards.net | 5 years ago

How to Hash and Verify Passwords With Argon2 in Go

Thanks to Andreas Auernhammer, author of the golang.org/x/crypto/argon2 package, for checking over this post before publication. If you're planning to store user passwords it's good practice (essential really) to hash them using a computationally expensive key-derivation function … | Continue reading


@alexedwards.net | 5 years ago

Practical Persistence in Go: Organising Database Access

Continue reading


@alexedwards.net | 5 years ago

Streamline Your Sublime Text + Go Workflow

For the past couple of years I've used Sublime Text as my primary code editor, along with the GoSublime plugin to provide some extra IDE-like features. But I've recently swapped GoSublime for a more modular plugin setup and have been really happy with the way it's worked out. Alt … | Continue reading


@alexedwards.net | 5 years ago

HTTP Method Spoofing in Go

A.K.A. HTTP method overriding. As a web developer you probably already know that HTML forms only support the GET and POST HTTP methods. If you want to send a PUT, PATCH or DELETE request you need to resort to either sending a XMLHttpRequest from JavaScript (where they are support … | Continue reading


@alexedwards.net | 6 years ago

How to build a Serverless API with Go and AWS Lambda

Earlier this year AWS announced that their Lambda service would now be providing first-class support for the Go language, which is a great step forward for any gophers (like myself) who fancy experimenting with serverless technology. So in this post I'm going to talk through how … | Continue reading


@alexedwards.net | 6 years ago

How to Disable http.FileServer Directory Listings

A nice feature of Go's http.FileServer is that it automatically generates navigable directory listings, which look a bit like this: But for certain applications you might want to prevent this behavior and disable directory listings altogether. In this post I’m going to run throu … | Continue reading


@alexedwards.net | 6 years ago

Configuring sql.DB for Better Performance

There are a lot of good tutorials which talk about Go's sql.DB type and how to use it to execute SQL database queries and statements. But most of them gloss over the SetMaxOpenConns(), SetMaxIdleConns() and SetConnMaxLifetime() methods — which you can use to configure the behavio … | Continue reading


@alexedwards.net | 6 years ago

How to Rate Limit HTTP Requests

If you're running a HTTP server and want to rate limit user requests, the go-to package to use is probably Tollbooth by Didip Kerabat. It's well maintained, has a good range of features and a clean and clear API. But if you want something simple and lightweight – or just want to … | Continue reading


@alexedwards.net | 6 years ago

Validation Snippets for Go

Over the past few years I've built up a collection of snippets for validating inputs in Go. There's nothing new or groundbreaking here, but hopefully they might save you some time. The snippets assume that the data to validate is stored as strings in r.Form, but the principles … | Continue reading


@alexedwards.net | 6 years ago

SCS: A session manager for Go 1.7+

I’ve just released SCS, a session management package for Go 1.7+. Its design leverages Go’s new context package to automatically load and save session data via middleware. Importantly, it also provides the security features that you need when using server-side session stores … | Continue reading


@alexedwards.net | 7 years ago

Working with Redis

In this post I'm going to be looking at using Redis as a data persistence layer for a Go application. We'll start by explaining a few of the essential concepts, and then build a working web application which highlights some techniques for using Redis in a concurrency-safe way. Th … | Continue reading


@alexedwards.net | 8 years ago

Practical Persistence in Go: SQL Databases

This is the first in a series of tutorials about persisting data in Go web applications. In this post we'll be looking at SQL databases. I'll explain the basics of the database/sql package, walk through building a working application, and explore a couple of options for cleanly … | Continue reading


@alexedwards.net | 8 years ago

Context-Aware Handler Chains in Go (using Stack)

I've written a package for chaining context-aware handlers in Go, called Stack. It was heavily inspired by Alice. What do you mean by 'context-aware'? If you're using a middleware pattern to process HTTP requests in Go, you may want to share some data or context between middl … | Continue reading


@alexedwards.net | 9 years ago

Making and Using HTTP Middleware

When you're building a web application there's probably some shared functionality that you want to run for many (or even all) HTTP requests. You might want to log every request, gzip every response, or check a cache before doing some expensive processing. One way of organising th … | Continue reading


@alexedwards.net | 9 years ago

Simple Flash Messages in Go

Often in web applications you need to temporarily store data in-between requests, such as an error or success message during the Post-Redirect-Get process for a form submission. Frameworks such as Rails and Django have the concept of transient single-use flash messages to help wi … | Continue reading


@alexedwards.net | 10 years ago

Form Validation and Processing in Go

In this post I want to outline a sensible pattern that you can use for validating and processing HTML forms in Go web applications. Over the years I've tried out a number of different approaches, but this is the basic pattern that I always keep coming back to. It's clear and unco … | Continue reading


@alexedwards.net | 10 years ago

HTTP Response Snippets for Go

Taking inspiration from the Rails layouts and rendering guide, I thought it'd be a nice idea to build a snippet collection illustrating some common HTTP responses for Go web applications. Sending Headers Only Rendering Plain Text Rendering JSON Rendering XML Ser … | Continue reading


@alexedwards.net | 10 years ago

Understanding Mutexes

For anyone new to building web applications with Go, it's important to realise that all incoming HTTP requests are served in their own Goroutine. This means that any code in or called by your application handlers will be running concurrently, and there is a risk of race condition … | Continue reading


@alexedwards.net | 10 years ago

Golang Automatic Reloads

I wrote a short Bash script to automatically reload Go programs. The script acts as a light wrapper around go run, stopping and restarting it whenever a .go file in your current directory or $GOPATH/src folder is saved. I've been using it mainly when developing web applications … | Continue reading


@alexedwards.net | 10 years ago

An Introduction to Handlers and Servemuxes in Go

Processing HTTP requests with Go is primarily about two things: handlers and servemuxes. If you’re coming from an MVC-background, you can think of handlers as being a bit like controllers. Generally speaking, they're responsible for carrying out your application logic and writing … | Continue reading


@alexedwards.net | 10 years ago

Serving Static Sites with Go

I've recently moved the site you're reading right now from a Sinatra/Ruby application to an (almost) static site served by Go. So while it's fresh in my head, here's an explanation of principles behind creating and serving static sites with Go. Let's begin with a simple but real- … | Continue reading


@alexedwards.net | 10 years ago

Cleaner, Better, Faster

I've never really known what to do with my personal site. Over the years it's been a dumping ground for links to different projects, and played host to various half-hearted attempts at blogging. But it's never really had much in the way of an actual purpose. I decided to start … | Continue reading


@alexedwards.net | 10 years ago