Gin in the wider system · 6 MIN READ
API versions in Gin: one service under /v1 and /v2, an adapter per version, and a v1 that announces its sunset
Serve two API versions from one service through per-version DTO adapters, mark v1 with Deprecation, Sunset and successor-version links, and test that v1 routes survive until the announced date.
A breaking change to a response shape cannot be deployed in place: some clients will keep sending yesterday's requests for months. The route-groups lesson put /v1 and /v2 groups side by side. This lesson adds what makes a second version manageable: a domain type that belongs to neither version, adapters that own each wire shape, standard headers that tell clients when v1 ends, and a route-table test that stops anyone from deleting v1 early.
gin · A MAP OF THE IDEA
- Map domain to DTOs
- Mark v1 in middleware
- Test the route table
- Retire on traffic
Useful when
- A bug fix in the service reaches both versions at once.
- Clients learn the end date and the replacement from standard headers.
- One Retirement value keeps headers and tests in agreement.
Watch out
- Group middleware does not run for 404 and 405, so typos carry no Sunset.
- Cross-origin clients cannot read the headers without Access-Control-Expose-Headers.
- A test that fails because v1 still exists after a date is a date bomb.
Implementation & operation cost: Two DTO sets and their adapters to maintain until the sunset, one middleware, and a route-table test; the real cost is the months of supporting v1 that the headers announce.
Version the wire shape, not the service
Suppose v1 returned a numeric id, a flat author string and a date, and the product now needs string IDs, a nested author object and a full timestamp. Changing the v1 handler breaks every mobile app that has not updated, and those apps update on their users' schedule, not yours. Copying the whole service into a v2 package fails differently: every bug fix now has to land twice, and the copies drift. The stable middle is one application service and one domain type that know nothing about JSON, plus one small adapter per version that maps the domain value to that version's DTO. A v1 handler and a v2 handler differ only in which adapter they call. Additive changes, such as a new optional field, do not need a new version; reserve /v2 for changes an old client cannot ignore. The compatibility lesson in the Go course covers the other half of the problem, when old and new binaries run during one rollout.
Two adapters, one service, and a v1 group that announces its end
The program keeps one Notes service and registers both groups on one engine. The v1 group carries a deprecated middleware built from a single Retirement value, which also feeds the route-table check, so the headers and the test can never disagree about the dates. The router receives its clock as a function, so the same engine can be asked what it does today and after the sunset.
package main
import (
"fmt"
"maps"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// Note is the domain type. Neither version's JSON shape lives here.
type Note struct {
ID int64
Author string
Created time.Time
}
type Notes struct{ byID map[int64]Note }
func (s *Notes) Get(id int64) (Note, bool) { n, ok := s.byID[id]; return n, ok }
func (s *Notes) List() []Note {
var out []Note
for _, id := range slices.Sorted(maps.Keys(s.byID)) {
out = append(out, s.byID[id])
}
return out
}
// v1 wire shape: numeric id, flat author, date only, bare array lists.
type noteV1 struct {
ID int64 `json:"id"`
Author string `json:"author"`
Created string `json:"created"`
}
// v2 wire shape: string id, nested author, RFC 3339 time, list envelope.
type authorV2 struct {
Name string `json:"name"`
}
type noteV2 struct {
ID string `json:"id"`
Author authorV2 `json:"author"`
CreatedAt string `json:"created_at"`
}
func toV1(n Note) noteV1 {
return noteV1{ID: n.ID, Author: n.Author, Created: n.Created.Format(time.DateOnly)}
}
func toV2(n Note) noteV2 {
return noteV2{ID: strconv.FormatInt(n.ID, 10), Author: authorV2{Name: n.Author},
CreatedAt: n.Created.UTC().Format(time.RFC3339)}
}
// Retirement is the v1 plan, kept in one place for headers and tests.
type Retirement struct {
Deprecated time.Time
Sunset time.Time
DocsURL string
Successors map[string]string // "GET /v1/..." route -> "GET /v2/..." route
}
func deprecated(rt Retirement, now func() time.Time) gin.HandlerFunc {
deprecation := "@" + strconv.FormatInt(rt.Deprecated.Unix(), 10)
sunset := rt.Sunset.UTC().Format(http.TimeFormat)
return func(c *gin.Context) {
h := c.Writer.Header()
h.Set("Deprecation", deprecation)
h.Set("Sunset", sunset)
links := []string{"<" + rt.DocsURL + `>; rel="deprecation"; type="text/html"`}
if next, ok := rt.Successors[c.Request.Method+" "+c.FullPath()]; ok {
_, template, _ := strings.Cut(next, " ")
links = append(links, "<"+fill(template, c)+`>; rel="successor-version"`)
}
h.Set("Link", strings.Join(links, ", "))
if !now().Before(rt.Sunset) {
c.AbortWithStatusJSON(http.StatusGone, gin.H{"error": "v1 has been retired; follow the successor-version link"})
return
}
c.Next()
}
}
// fill turns "/v2/notes/:id" into "/v2/notes/7" using this request's parameters.
func fill(template string, c *gin.Context) string {
parts := strings.Split(template, "/")
for i, p := range parts {
if name, ok := strings.CutPrefix(p, ":"); ok {
parts[i] = url.PathEscape(c.Param(name))
}
}
return strings.Join(parts, "/")
}
func noteID(c *gin.Context) (int64, bool) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
return id, err == nil && id > 0
}
func newRouter(notes *Notes, rt Retirement, now func() time.Time) *gin.Engine {
r := gin.New()
v1 := r.Group("/v1", deprecated(rt, now))
v1.GET("/notes", func(c *gin.Context) {
out := []noteV1{}
for _, n := range notes.List() {
out = append(out, toV1(n))
}
c.JSON(http.StatusOK, out)
})
v1.GET("/notes/:id", func(c *gin.Context) {
id, ok := noteID(c)
n, found := notes.Get(id)
if !ok || !found {
c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
return
}
c.JSON(http.StatusOK, toV1(n))
})
v2 := r.Group("/v2")
v2.GET("/notes", func(c *gin.Context) {
items := []noteV2{}
for _, n := range notes.List() {
items = append(items, toV2(n))
}
c.JSON(http.StatusOK, gin.H{"items": items, "next": nil})
})
v2.GET("/notes/:id", func(c *gin.Context) {
id, ok := noteID(c)
n, found := notes.Get(id)
if !ok || !found {
c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
return
}
c.JSON(http.StatusOK, toV2(n))
})
return r
}
// checkRetirement is the route-table test: v1 stays until its sunset and
// every v1 route points at a successor that is really registered.
func checkRetirement(routes gin.RoutesInfo, rt Retirement, now time.Time) []string {
have := map[string]bool{}
for _, r := range routes {
have[r.Method+" "+r.Path] = true
}
var problems []string
for _, r := range routes {
key := r.Method + " " + r.Path
if strings.HasPrefix(r.Path, "/v1/") && rt.Successors[key] == "" {
problems = append(problems, key+" has no successor-version mapping")
}
}
for _, old := range slices.Sorted(maps.Keys(rt.Successors)) {
if !have[old] && now.Before(rt.Sunset) {
problems = append(problems, old+" removed before its sunset "+rt.Sunset.Format(time.DateOnly))
}
if next := rt.Successors[old]; !have[next] {
problems = append(problems, "successor "+next+" is not registered")
}
}
slices.Sort(problems)
return problems
}
func report(label string, problems []string) {
if len(problems) == 0 {
fmt.Println(label + ": ok")
return
}
for _, p := range problems {
fmt.Println(label + ": " + p)
}
}
func main() {
gin.SetMode(gin.TestMode)
notes := &Notes{byID: map[int64]Note{
7: {ID: 7, Author: "Platform Team", Created: time.Date(2026, 11, 1, 9, 30, 0, 0, time.UTC)},
}}
rt := Retirement{
Deprecated: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC),
Sunset: time.Date(2027, 5, 1, 0, 0, 0, 0, time.UTC),
DocsURL: "https://docs.example.com/api/v1-retirement",
Successors: map[string]string{
"GET /v1/notes": "GET /v2/notes",
"GET /v1/notes/:id": "GET /v2/notes/:id",
},
}
today := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
afterSunset := time.Date(2027, 5, 2, 0, 0, 0, 0, time.UTC)
clock := today
r := newRouter(notes, rt, func() time.Time { return clock })
call := func(path string) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
fmt.Println(clock.Format(time.DateOnly), "GET", path, w.Code, w.Body.String())
for _, k := range []string{"Deprecation", "Sunset", "Link"} {
if v := w.Header().Get(k); v != "" {
fmt.Printf(" %s: %s\n", k, v)
}
}
}
call("/v1/notes/7")
call("/v2/notes/7")
call("/v2/notes")
clock = afterSunset
call("/v1/notes")
routes := r.Routes()
report("table today", checkRetirement(routes, rt, today))
trimmed := slices.DeleteFunc(slices.Clone(routes), func(ri gin.RouteInfo) bool {
return ri.Method == http.MethodGet && ri.Path == "/v1/notes"
})
report("v1 list deleted today", checkRetirement(trimmed, rt, today))
report("v1 list deleted after sunset", checkRetirement(trimmed, rt, afterSunset))
}toV1 and toV2 are the only code that knows either wire shape; handlers fetch a Note and pick an adapter. deprecated computes both header values once: Deprecation is a structured-field date, an at sign followed by Unix seconds, and Sunset is an HTTP-date from http.TimeFormat. Per request it looks up the method and c.FullPath(), the route template, in Successors and fills the v2 template with this request's parameters, so /v1/notes/7 links to /v2/notes/7. Once the injected clock passes the sunset, v1 answers 410 Gone but keeps its links. checkRetirement reads r.Routes(): a v1 route missing before the sunset is a finding, after it the removal is allowed, and every successor must be registered.
What Deprecation, Sunset and successor-version promise
The three headers answer different client questions. Deprecation (RFC 9745) says the resource is deprecated, or will be, as of a date; it changes nothing about how the request is processed. Sunset (RFC 8594) says when the resource is expected to stop responding, and RFC 9745 adds that the sunset should not be earlier than the deprecation date; a sunset in the past means the resource may vanish at any moment. A Link with rel="successor-version" (RFC 5829) names the replacement, and rel="deprecation" points people at migration notes. Set all of them in group middleware before c.Next, because a header added after the handler has started the body is silently not sent. Know what the middleware cannot reach: Gin's 404 and 405 answers run only engine-level middleware, so a mistyped v1 path carries no Sunset. Browsers hide these headers from cross-origin scripts unless the CORS middleware lists them in Access-Control-Expose-Headers. After the sunset, 410 Gone with the successor link is kinder than 404: it tells a client the path was real and where it went.
Keep version differences inside the adapters
Adapters run in both directions. A v1 POST body should be decoded into a v1 request DTO and translated into the same domain command v2 uses, so validation and side effects stay in one place. Do not implement v1 by calling the v2 handler and rewriting its JSON: you pay two encodings, and v1 quietly inherits every later v2 change, including ones its clients must not see. Watch for semantic changes that no type shows: if v2 reports durations in milliseconds and v1 in seconds, the conversion belongs in toV1 and in a test. A golden test per adapter, with one captured v1 response checked in as a fixture, catches accidental changes to the old shape when someone edits the domain type. Path versioning, as here, is the easiest scheme to route, cache and label in metrics; with header or media-type versioning, every cache key, log query and dashboard has to learn the header too.
A route-table test that cannot become a date bomb
checkRetirement takes the time as a parameter. Its own unit tests pin dates on both sides of the sunset, as the program does, so their outcome never changes. The guard on the real router passes time.Now(): until the announced date, deleting a v1 route fails CI, and from the sunset on the same test permits the deletion without anyone editing it. The opposite rule, failing the build because v1 still exists after the sunset, is a date bomb that breaks an unrelated pull request on a calendar day. Track the clean-up with traffic instead: count requests by c.FullPath() as the metrics lesson does, and remove the v1 group when its remaining callers are clients you have contacted, not merely when the date passes.
func TestV1RoutesSurviveUntilSunset(t *testing.T) {
gin.SetMode(gin.TestMode)
r := newRouter(seedNotes(), retirement, time.Now)
for _, problem := range checkRetirement(r.Routes(), retirement, time.Now()) {
t.Error(problem)
}
}
func TestCheckRetirementAroundSunset(t *testing.T) {
gin.SetMode(gin.TestMode)
r := newRouter(seedNotes(), retirement, time.Now)
routes := slices.DeleteFunc(r.Routes(), func(ri gin.RouteInfo) bool {
return ri.Method == http.MethodGet && ri.Path == "/v1/notes"
})
if got := checkRetirement(routes, retirement, retirement.Sunset.Add(-time.Hour)); len(got) != 1 {
t.Fatalf("before sunset: got %q, want one removal finding", got)
}
if got := checkRetirement(routes, retirement, retirement.Sunset); len(got) != 0 {
t.Fatalf("at sunset: got %q, want none", got)
}
}This fragment belongs in a _test.go file beside newRouter; retirement and seedNotes are the package's own values. The first test guards the real router with the real clock, so it relaxes by itself at the sunset. The second pins both sides of the boundary: an hour before the sunset the deleted list route is exactly one finding, and at the sunset instant, where Before is false, there are none. r.Routes() builds a fresh slice on every call, so DeleteFunc cannot change the engine.
TAKE THIS WITH YOU
Keep the domain version-free and give each version an adapter; put the retirement dates in one value that drives the Deprecation, Sunset and successor-version headers and a route-table test that receives its clock.
Check your understanding
A v1 group sends Deprecation and Sunset headers and points to /v2 with successor-version links. When is it safe to delete a v1 route registration?
Go to the source
Progress stays in this browser. No account needed.