V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
darklowly
V2EX  ›  程序员

如何设计 restful bool 查询?

  •  
  •   darklowly · 2020-05-28 10:12:10 +08:00 · 500 次点击
    这是一个创建于 1439 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假设有如下模型:

    type User struct {
        Name    string
        Enabled bool  // 这是一个 bool 类型的字段
        Online  bool  // 这是一个 bool 类型的字段
    
        //
        // 其他字段...
        //
    }
    

    那么在设计 restful 接口的时候,应该如何支持如下功能:

    1 创建一个用户

    POST /api/v1/users
    {
        "name": "hello",
        "enabled": true // 可选,默认为 true
    }
    
    // 对应的 golang 结构为
    type CreateUserReq struct {
        Name    string
        Enabled bool // 注意:这里是有问题的
    }
    

    2 查询所有用户,支持查询 [全部用户] [活跃用户] [不活跃的用户]

    GET /api/v1/users               // 查询全部用户
    GET /api/v1/users?actived=true  // 查询活跃用户
    GET /api/v1/users?actived=false // 查询不活跃用户
    
    // 对应的 golang 结构为
    type ListUserReq struct {
        Enabled bool // 注意:这里是有问题的
    }
    

    我现在能想到的方法有 5 种:

    方法零:修改 Enabled 字段为 Disabled 不算是一种方法,因为在查询所有用户的时候,还是会有问题

    方法一: 坚持用 bool,那么在解析 http 请求的时候,需要放弃 struct,用 map

    方法二: 用 bool 指针,代码检测会很麻烦,因为指针可能为 nil,不小心会引入 panic

    type CreateUserReq struct {
        Name    string
        Enabled *bool // 这里是指针
    }
    

    方法三:用 int,0 表示关闭,1 表示开启,因为 golang 有默认值,所以这种方案比 bool 还差

    const (
        Disabled = 0 // 注意
        Enabled  = 1 // 注意
    )
    
    type CreateUserReq struct {
        Name    string
        Enabled int // 注意
    }
    

    方法四:用 int,1 表示关闭,2 表示开启,但是会违反程序员的直觉,因为程序员的直觉会觉得 0 是 false,其他为 true

    const (
        Disabled = 1 // 注意
        Enabled  = 2 // 注意
    )
    
    type CreateUserReq struct {
        Name    string
        Enabled int // 注意
    }
    

    方法五:用字符串表示,actived 表示活跃,inactived 表示不活跃

    const (
        Enabled  = "enabled"  // 注意
        Disabled = "disabled" // 注意
    )
    
    type CreateUserReq struct {
        Name    string
        Enabled string // 注意
    }
    

    请问一般解决这种问题的惯用方法是什么?

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1028 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 19:18 · PVG 03:18 · LAX 12:18 · JFK 15:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.