我正在测试Goa的API。我想使用uuid作为ID数据类型。我修改了controller.go中的以下函数:
// Show runs the show action.
func (c *PersonnelController) Show(ctx *app.ShowPersonnelContext) error {
// v4 UUID validate regex
var validate = `^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[8|9|aA|bB][a-f0-9]{3}-[a-f0-9]{12}$`
uuidValidator := regexp.MustCompile(validate)
if !uuidValidator.Match(ctx.MemberID) {
return ctx.NotFound()
}
// Build the resource using the generated data structure
personnel := app.GoaCrewWorkforce{
MemberID: ctx.MemberID,
FirstName: fmt.Sprintf("First-Name #%s", ctx.MemberID),
LastName: fmt.Sprintf("Last-Name #%s", ctx.MemberID),
}
我想要做的是使用Regexp在我的控制器中验证v4 uuid,这样如果它没有验证它就不会轮询服务器。这是我的理解,uuid是[16]字节切片。 Regexp具有Match
[]字节函数。但我似乎无法理解为什么会出现以下错误:
cannot use ctx.MemberID (type uuid.UUID) as type []byte in argument to uuidValidator.Match
如何输入assert ctx.MemberID?在这种情况下,我认为不可能进行强制转换?任何指导都表示赞赏。
答案 0 :(得分:1)
如果要验证uuid,可以直接检查位。由于16个字节中的大多数是随机的,因此可以检查版本号的第6个字节的前4位,或者变量的第8个字节的前3位,因此验证不多。
// enforce only V4 uuids
if ctx.MemberID[6] >> 4 != 4 {
log.Fatal("not a V4 UUID")
}
// enforce only RFC4122 type UUIDS
if (ctx.MemberID[8]&0xc0)|0x80 != 0x80 {
log.Fatal("not an RFC4122 UUID")
}