如何为 Gin 编写一个 mobile 绑定器,自动校验中国大陆手机号并返回标准格式?
解读
面试官想考察三件事:
- 对 Gin 绑定器(binding)扩展机制的理解,能否脱离 JSON、Form 等官方标签,自定义结构体字段的“取值→校验→改写”全流程。
- 对中国大陆手机号规则的严谨掌握:号段、长度、前缀 0 与 +86 的兼容、虚拟运营商、携号转网后的合法性判断。
- 工程化思维:错误信息如何与 Gin 的 validator 生态打通、性能是否零分配、是否支持并发、单测如何写。
一句话:不是“写个正则”,而是“写个生产级、可复用、对业务无侵入的 Gin 扩展”。
知识点
- Gin 绑定管线:
ShouldBindJSON→binding.JSON→json.Unmarshal→validate.Struct。
自定义绑定器需实现binding.Binding接口:Name() string、Bind(*http.Request, interface{}) error。 - Go 1.20+ 的
regexp内部已做sync.Pool缓存,但预编译仍比每次Compile快 10 倍以上。 - 中国大陆最新号段(2024 版):
移动 134-139/147/150-152/157-159/172/178/182-184/187-188/195/197-198
联通 130-132/145/155-156/166/175/176/185-186/196
电信 133/149/153/173/174/177/180-181/189/190-191/193-199
广电 192
物联网 140-144/146/148/149
总长度 11 位,不能以 0 开头,前 3 位必须在上述集合。 - 标准格式约定:返回
8613xxxxxxxxx,去掉所有空格、短横线、括号,前缀0替换成86,+86直接截成86。 - 错误返回需兼容 Gin 的
validator.ValidationErrors,前端可直接用field + tag做 i18n。 - 单测必须覆盖:非法长度、非法号段、带国际前缀、带中间空格、并发绑定。
答案
package binder
import (
"errors"
"net/http"
"regexp"
"strings"
"sync"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
var (
mobileRegex = regexp.MustCompile(`^(\+?86)?0?1([3-9])\d{9}$`)
once sync.Once
)
// Mobile 类型标记,用于结构体字段
type Mobile string
// MobileBinding 实现 gin.binding.Binding 接口
type MobileBinding struct{}
func (MobileBinding) Name() string {
return "mobile"
}
func (MobileBinding) Bind(req *http.Request, obj interface{}) error {
once.Do(func() {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("mobile", validateMobile)
}
})
// 只处理 query 或 form 中的单个字段,JSON 场景由 validator 标签接管
values := req.URL.Query()
if len(values) == 0 {
values = req.Form
}
raw := values.Get("mobile")
if raw == "" {
return nil // 留空由 required 标签处理
}
std, err := normalizeMobile(raw)
if err != nil {
return err
}
if ptr, ok := obj.(*Mobile); ok {
*ptr = Mobile(std)
return nil
}
return errors.New("mobile: destination must be *Mobile")
}
// 校验函数,供 validator 标签使用
func validateMobile(fl validator.FieldLevel) bool {
_, err := normalizeMobile(fl.Field().String())
return err == nil
}
// normalizeMobile 统一返回 8613xxxxxxxxx
func normalizeMobile(s string) (string, error) {
s = strings.ReplaceAll(s, " ", "")
s = strings.ReplaceAll(s, "-", "")
s = strings.TrimPrefix(s, "+")
if !mobileRegex.MatchString(s) {
return "", &MobileError{msg: "invalid mainland china mobile"}
}
s = strings.TrimPrefix(s, "86")
if strings.HasPrefix(s, "0") {
s = s[1:]
}
return "86" + s, nil
}
type MobileError struct {
msg string
}
func (e *MobileError) Error() string { return e.msg }
// 让 MobileError 可以被 validator.ValidationErrors 识别
func (e *MobileError) Translate(ut validator.Translator) error {
return ut.Add("mobile", "{0} must be valid china mobile", true)
}
使用示例:
type LoginReq struct {
Mobile binder.Mobile `form:"mobile" json:"mobile" binding:"required,mobile"`
Code string `json:"code" binding:"required,len=6"`
}
func login(c *gin.Context) {
var req LoginReq
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// req.Mobile 已经是 8613xxxxxxxxx
c.JSON(http.StatusOK, gin.H{"mobile": req.Mobile})
}
性能:
- 正则预编译,零分配绑定路径。
- 并发安全:正则内部已加锁,binding 实例无状态。
单测(节选):
func TestNormalizeMobile(t *testing.T) {
for _, tc := range []struct {
in string
out string
ok bool
}{
{"+86 138-0013-8000", "8613800138000", true},
{"013800013800", "8613800013800", true},
{"13812345678", "8613812345678", true},
{"19812345678", "8619812345678", true},
{"12812345678", "", false},
{"12345678901", "", false},
} {
got, err := normalizeMobile(tc.in)
if (err == nil) != tc.ok || got != tc.out {
t.Errorf("normalizeMobile(%q) = (%q, %v); want (%q, %v)",
tc.in, got, err, tc.out, tc.ok)
}
}
}
拓展思考
- 号段白名单热更新:把号段列表放到 etcd / Consul,监听变更后原子替换
mobileRegex,无需重启服务。 - 多国家地区扩展:把
Mobile改成接口Normalizer,不同国家实现不同策略,路由层根据X-Region头选择绑定器。 - 防刷场景:在绑定器里直接对接风控接口,发现虚拟运营商或高危号段直接返回 429,减少一次业务层调用。
- 与 OpenAPI 集成:自定义
mobile格式,让 swag 自动生成为{"type":"string","pattern":"^861[3-9]\\d{9}$"},前端表单实时校验。