mirror of
https://github.com/chai2010/advanced-go-programming-book.git
synced 2025-05-24 04:22:22 +00:00
update validator
This commit is contained in:
parent
305371367f
commit
aa78fb7a2b
@ -4,7 +4,11 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
实际上这是一个语言无关的场景,需要进行字段校验的情况有很多,web 系统的 Form/json 提交只是一个典型的例子。我们用 go 来写一个类似上图的校验 demo。然后研究怎么一步步对其进行改进。假设我们的数据已经通过某个 binding 库绑定到了具体的 struct 上。
|
实际上这是一个语言无关的场景,需要进行字段校验的情况有很多,web 系统的 Form/json 提交只是一个典型的例子。我们用 go 来写一个类似上图的校验 demo。然后研究怎么一步步对其进行改进。
|
||||||
|
|
||||||
|
## 重构请求校验函数
|
||||||
|
|
||||||
|
假设我们的数据已经通过某个 binding 库绑定到了具体的 struct 上。
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type RegisterReq struct {
|
type RegisterReq struct {
|
||||||
@ -63,4 +67,6 @@ func register(req RegisterReq) error{
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
代码更清爽,看起来也不那么别扭了。这是比较通用的重构理念。
|
代码更清爽,看起来也不那么别扭了。这是比较通用的重构理念。虽然使用了重构方法使我们的 validate 过程看起来优雅了,但我们还是得为每一个 http 请求都去写这么一套差不多的 validate 函数,有没有更好的办法来帮助我们解除这项体力劳动?答案就是 validator。
|
||||||
|
|
||||||
|
## 用 validator 解放体力劳动
|
||||||
|
Loading…
x
Reference in New Issue
Block a user