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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Custom struct-tag validators let you push domain rules into binding instead of scattering checks through handlers.
- 2Reaching into Gin's underlying validator engine gives you a hook to register application-specific rules once at startup.
- 3Distinguishing validation errors from other bind failures lets you return precise, field-level feedback with the right status code.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 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/a-custom-gin-validator-backed-by-redis-explained-go-2f53/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.