go 61 lines · 9 steps

Sparse fieldsets in a Gin handler

A Gin endpoint lets clients pick which user fields come back via a ?fields= query parameter.

Explained by highlit
1package handlers
2 
3import (
4 "net/http"
5 "strings"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10type User struct {
11 ID int `json:"id"`
12 Name string `json:"name"`
13 Email string `json:"email"`
14 Role string `json:"role"`
15 CreatedAt string `json:"created_at"`
16}
17 
18func sparseFields(c *gin.Context) map[string]bool {
19 raw := c.Query("fields")
20 if raw == "" {
21 return nil
22 }
23 fields := make(map[string]bool)
24 for _, f := range strings.Split(raw, ",") {
25 if f = strings.TrimSpace(f); f != "" {
26 fields[f] = true
27 }
28 }
29 return fields
30}
31 
32func project(u User, fields map[string]bool) map[string]any {
33 full := map[string]any{
34 "id": u.ID,
35 "name": u.Name,
36 "email": u.Email,
37 "role": u.Role,
38 "created_at": u.CreatedAt,
39 }
40 if fields == nil {
41 return full
42 }
43 partial := make(map[string]any, len(fields))
44 for key, val := range full {
45 if fields[key] {
46 partial[key] = val
47 }
48 }
49 return partial
50}
51 
52func GetUser(userService UserService) gin.HandlerFunc {
53 return func(c *gin.Context) {
54 user, err := userService.FindByID(c.Request.Context(), c.Param("id"))
55 if err != nil {
56 c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
57 return
58 }
59 c.JSON(http.StatusOK, project(user, sparseFields(c)))
60 }
61}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning nil as a sentinel lets one code path cleanly distinguish 'no filter' from 'empty filter'.
  2. 2Projecting a struct into a map[string]any gives you dynamic, client-driven response shapes.
  3. 3A handler that closes over its dependencies keeps route wiring testable and decoupled.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Sparse fieldsets in a Gin handler — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code