go
31 lines · 7 steps
Conditional GET with ETags in Gin
A Gin handler that fetches an article and skips resending it when the client's cached copy is still fresh.
Explained by
highlit
1func GetArticle(c *gin.Context) {
2 id := c.Param("id")
3
4 article, err := articleRepo.FindByID(c.Request.Context(), id)
5 if err != nil {
6 if errors.Is(err, sql.ErrNoRows) {
7 c.JSON(http.StatusNotFound, gin.H{"error": "article not found"})
8 return
9 }
10 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load article"})
11 return
12 }
13
14 etag := fmt.Sprintf(`"%x"`, sha1.Sum([]byte(fmt.Sprintf("%s-%d", article.ID, article.UpdatedAt.UnixNano()))))
15
16 if match := c.GetHeader("If-None-Match"); match != "" {
17 for _, tag := range strings.Split(match, ",") {
18 tag = strings.TrimSpace(tag)
19 if tag == etag || tag == "*" {
20 c.Header("ETag", etag)
21 c.Header("Cache-Control", "private, must-revalidate")
22 c.Status(http.StatusNotModified)
23 return
24 }
25 }
26 }
27
28 c.Header("ETag", etag)
29 c.Header("Cache-Control", "private, must-revalidate")
30 c.JSON(http.StatusOK, article)
31}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1ETags let a server answer with 304 Not Modified so unchanged bodies never travel the wire twice.
- 2Deriving the ETag from stable identity plus a modification timestamp makes it change exactly when the resource does.
- 3Distinguishing a not-found error from an unexpected failure lets clients react to each correctly.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/conditional-get-with-etags-in-gin-explained-go-205a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.