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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
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.