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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning nil as a sentinel lets one code path cleanly distinguish 'no filter' from 'empty filter'.
- 2Projecting a struct into a map[string]any gives you dynamic, client-driven response shapes.
- 3A handler that closes over its dependencies keeps route wiring testable and decoupled.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
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/sparse-fieldsets-in-a-gin-handler-explained-go-bac2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.