在写 Golang 的 WebServer 时我就很难受,缺一个类似 Node.js 的 joi 的框架,有很多想写的规则写不出来。
在 Golang 社区中参数校验一般是用 https://github.com/go-playground/validator 或者 https://github.com/astaxie/beego/tree/develop/validation 这些类似的东西。
我在使用这类框架的时候遇到了两个问题:
先给个 jio 的使用例子
package main
import (
"errors"
"io/ioutil"
"net/http"
"github.com/faceair/jio"
"github.com/go-chi/chi"
)
func main() {
r := chi.NewRouter()
r.Route("/people", func(r chi.Router) {
r.With(jio.ValidateBody(jio.Object().Keys(jio.K{
"name": jio.String().Transform(func(ctx *jio.Context) {
if ctx.Value != "faceair" {
ctx.Abort(errors.New("you are not faceair"))
}
}).Required(),
"age": jio.Number().Integer().Min(0).Max(100).Required(),
"phone": jio.String().Regex(`^1[34578]\d{9}$`).Required(),
}), jio.DefaultErrorHandler)).Post("/", func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader( http.StatusOK)
w.Write(body)
})
})
http.ListenAndServe(":8080", r)
}
我是这么解决这些问题的。
同时 jio 还能给参数设置默认值、帮你做类型转换(string 转 array 转 int 等等)、能选择校验规则的顺序、能根据其他字段的数据选择不同的校验规则等等,我觉得 jio 灵活性比任何一个校验框架都要好(也包括 joi)。
更多的使用文档可以直接查看 https://github.com/faceair/jio/blob/master/README.zh.md 欢迎大家多多使用,可以给 star 鼓励,也可以给与一些反馈我好继续迭代改进。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.