go 57 lines · 8 steps

A custom Gin validator backed by Redis

Register a struct-tag validator that checks coupon codes against a live Redis set, then wire it into Gin's binding flow.

Explained by highlit
1package handlers
2 
3import (
4 "context"
5 "net/http"
6 "strings"
7 "time"
8 
9 "github.com/gin-gonic/gin"
10 "github.com/gin-gonic/gin/binding"
11 "github.com/go-playground/validator/v10"
12 "github.com/redis/go-redis/v9"
13)
14 
15type checkoutRequest struct {
16 Items []string `json:"items" binding:"required,min=1,dive,required"`
17 CouponCode string `json:"coupon_code" binding:"omitempty,coupon"`
18}
19 
20func RegisterCouponValidator(rdb *redis.Client) error {
21 v, ok := binding.Validator.Engine().(*validator.Validate)
22 if !ok {
23 return nil
24 }
25 return v.RegisterValidation("coupon", func(fl validator.FieldLevel) bool {
26 code := strings.ToUpper(strings.TrimSpace(fl.Field().String()))
27 if code == "" {
28 return false
29 }
30 ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
31 defer cancel()
32 ok, err := rdb.SIsMember(ctx, "coupons:active", code).Result()
33 return err == nil && ok
34 })
35}
36 
37func Checkout(c *gin.Context) {
38 var req checkoutRequest
39 if err := c.ShouldBindJSON(&req); err != nil {
40 var verrs validator.ValidationErrors
41 if errors.As(err, &verrs) {
42 fields := make(map[string]string, len(verrs))
43 for _, fe := range verrs {
44 fields[fe.Field()] = fe.Tag()
45 }
46 c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": fields})
47 return
48 }
49 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
50 return
51 }
52 
53 c.JSON(http.StatusAccepted, gin.H{
54 "items": req.Items,
55 "coupon": strings.ToUpper(req.CouponCode),
56 })
57}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Custom struct-tag validators let you push domain rules into binding instead of scattering checks through handlers.
  2. 2Reaching into Gin's underlying validator engine gives you a hook to register application-specific rules once at startup.
  3. 3Distinguishing validation errors from other bind failures lets you return precise, field-level feedback with the right status code.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A custom Gin validator backed by Redis — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code