govalidator----结构体tag验证

github地址:https://github.com/asaskevich/govalidator

govalidator支持内置支持的验证tag和自定义验证tag:

package main

import (
    "github.com/asaskevich/govalidator"
    "fmt"
    "strings"
)

type Server struct {
    ID         string `valid:"uuid,required"`
    Name       string `valid:"machine_id"`
    HostIP     string `valid:"ip"`
    MacAddress string `valid:"mac,required"`
    WebAddress string `valid:"url"`
    AdminEmail string `valid:"email"`
}

func main() {
    server := &Server{
        ID:         "123e4567-e89b-12d3-a456-426655440000",
        Name:       "IX01",
        HostIP:     "127.0.0.1",
        MacAddress: "01:23:45:67:89:ab",
        WebAddress: "www.example.com",
        AdminEmail: "admin@exmaple.com",
    }

    //自定义tag验证函数   machine_id就是自定义的tag
    govalidator.TagMap["machine_id"] = govalidator.Validator(func(str string) bool {
        return strings.HasPrefix(str, "IX")
    })

    if ok, err := govalidator.ValidateStruct(server); err != nil {
        panic(err)
    } else {
        fmt.Printf("OK: %v\n", ok)
    }
}

 

posted @ 2018-11-28 17:59  静静别跑  阅读(1510)  评论(0编辑  收藏  举报