The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
matthewgao

撸了一个校验 JSON 内容的工具,解决 golang API 调用请求内容校验的麻烦事

  •  
  •   matthewgao ·
    matthewgao · Oct 14, 2017 · 2710 views
    This topic created in 3140 days ago, the information mentioned may be changed or developed.

    API 经常都是用 JSON 来传递参数的,golang 里 unmarshal 之后总要自己做各种参数校验,好烦,尤其是 json 很长的时候,所以用 reflect 撸了个参数自动校验的东东,请大家多指教,提意见

    https://github.com/matthewgao/gojsonvalidator

    18 replies    2017-10-19 17:42:06 +08:00
    eoo
        1
    eoo  
       Oct 14, 2017 via Android
    golang 处理 json 很麻烦吗?
    matthewgao
        2
    matthewgao  
    OP
       Oct 14, 2017
    @eoo unmarshal 容易,但是往往要校验里面值是否合法,这个比较讨厌
    eoo
        3
    eoo  
       Oct 14, 2017 via Android
    @matthewgao 按道理 这应该由语言本身实现合法性验证,这不是反古了?
    matthewgao
        4
    matthewgao  
    OP
       Oct 14, 2017
    @eoo 我指的是业务层面的校验,比如 json 里一个 age 字段 我希望输入一个合法范围是 16-30,其他的都是不合法的输入
    polythene
        5
    polythene  
       Oct 14, 2017
    赞,很方便的样子
    eoo
        6
    eoo  
       Oct 14, 2017 via Android
    @matthewgao 这就尴尬了 理解错了...... 大神 求带
    vus520
        7
    vus520  
       Oct 14, 2017
    golang 处理 json 很麻烦吗?

    是很、非常、特别
    youEclipse
        8
    youEclipse  
       Oct 14, 2017
    不少框架都有带参数校验,最近看到一个框架用的这个,看起来还不错 https://github.com/go-macaron/binding
    miyuki
        9
    miyuki  
       Oct 14, 2017 via Android
    go 处理复杂 json …怎么说呢
    matthewgao
        10
    matthewgao  
    OP
       Oct 14, 2017
    @youEclipse 看起来跟我思路差不多,这个框架跟 beego 比怎么样?
    matthewgao
        11
    matthewgao  
    OP
       Oct 14, 2017
    @eoo 我也是小白。。
    scofieldpeng
        12
    scofieldpeng  
       Oct 14, 2017   ❤️ 1
    首先回楼上的,golang 处理起来确实很麻烦,其二回楼主,其实有轮子了的,一般用这个,比较强大 https://github.com/asaskevich/govalidator
    boboliu
        13
    boboliu  
       Oct 14, 2017 via Android
    boboliu
        14
    boboliu  
       Oct 14, 2017 via Android
    @scofieldpeng 刚才手抖了。。。感谢推荐,看起来很不错
    ligyxy
        15
    ligyxy  
       Oct 14, 2017 via Android
    matthewgao
        16
    matthewgao  
    OP
       Oct 14, 2017
    @scofieldpeng 我大概看下,可能没太看全 有一个场景似乎和我期待的不太一样,就是如何区分一个 unmarshal 出来的值到底是默认值还是调用方指定的值,并且如果是调用方未指定的要给一个默认值。
    其实最搞的就是 int, bool 这两个类型,0 和 false 这两个默认值很尴尬,除非在 unmarshal 之前显示的设置好初始值,但是这又不是很优雅
    scofieldpeng
        17
    scofieldpeng  
       Oct 15, 2017
    @matthewgao 它只能做那种通用的,不过已经减少了很多功夫了,对于高阶的判断我一般对于会在所有的 struct 附加一个 func Valid() error 方法,在它之后调用这个,仅供参考,对于默认值 0 和 false 这种确实不好判断,一般我都是尽量避免使用 false 和 0 的条件
    HarrisonZ
        18
    HarrisonZ  
       Oct 19, 2017
    api 输出 json,cs,ss 通讯都是 grpc,来回类型转换搞得简直要吐
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5324 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 84ms · UTC 07:00 · PVG 15:00 · LAX 00:00 · JFK 03:00
    ♥ Do have faith in what you're doing.