V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
dzdh
V2EX  ›  Go 编程语言

有没有什么优雅的方法实现 当 req.xx == yy 时 某些参数必须 或转成其他 struct

  •  
  •   dzdh · 61 天前 · 1506 次点击
    这是一个创建于 61 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一个 api 中转系统

    当 body json channel==app1 时,data.somekey required 。否则 [必须不传]

    其他类似 channel=app2 时 data.somekey2 required 否则 [必须不传]

    现在是这么干的

    type tmp struct { C string json:"channel" }

    gin.get("/", func... c.bind(C) switch(channel) case xx: return new ChannelXX(c.req)

    第 1 条附言  ·  61 天前

    没写完 继续贴

    不同的channel有对应不同的process方法

    比如 func channelAProcess(name, price, attr string) func channelBProcess(name, attr)

    req里对应的channel,获取指定的对应需要的参数 然后调用对应的channelprocess方法。如果方法多了维护是个问题。

    有什么好的方案吗

    9 条回复    2024-07-09 11:20:10 +08:00
    gam2046
        1
    gam2046  
       61 天前   ❤️ 1
    唔,我重复看了两遍,可是没看懂,你想要表达的意思。
    0o0O0o0O0o
        2
    0o0O0o0O0o  
       61 天前
    0o0O0o0O0o
        3
    0o0O0o0O0o  
       61 天前   ❤️ 1
    henix
        4
    henix  
       61 天前
    somekey, somekey2 的类型改为自己实现的 json.Unmarshaler 然后外面加上自定义验证逻辑?
    Ayanokouji
        5
    Ayanokouji  
       61 天前
    要优雅的话,可以用 cue
    https://cuelang.org/
    424778940
        6
    424778940  
       60 天前
    不太理解这个需求, 为什么要求"必须不传"?

    不然直接用 protobuf3 不好吗?
    dzdh
        7
    dzdh  
    OP
       60 天前
    @424778940

    某种程度上来说,就是降低心智负担。某个 channel 的参数白名单是什么,这个 channel 下,其他参数,是不能游泳的,不生效的,所以,干脆就不要传。

    http json api 。不想引入太多新东西。
    qh666
        8
    qh666  
       60 天前
    使用 https://github.com/go-playground/validator 校验即可
    类似于这种接第三方 api 的应用推荐使用
    github.com/go-resty/resty

    个人建议是早期先引入此类成熟的工具库,否则后期不好改动,只能硬着头皮去维护了

    参考

    validated.BindAndValidatePostJson()

    type LoginReq struct {
    Phone string `json:"phone" binding:"omitempty,required_if=Type 1,required_if=Type 2,phone,len=11"` // 手机号
    Type int `json:"type" binding:"required,oneof=1 2 3 4"` // 1 短信验证码登录 2 账号密码登录
    }
    424778940
        9
    424778940  
       60 天前
    @dzdh 这两个并不冲突啊

    不能有用的参数接收方不处理不就完了, 不然调用方还要特地区分每个情况下哪个参数能不能传才是心智负担吧

    不想引入太多东西往往意味着要自己写更多的东西重新实现现成的轮子的一部分
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1990 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 00:04 · PVG 08:04 · LAX 17:04 · JFK 20:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.