Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

如何设计 restful bool 查询?

假设有如下模型:

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 // 注意
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...