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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.