使用反射对绑定url参数到结构体

通过反射自动绑定url参数到结构体,同时支持对参数范围进行校验已经参数默认值的设置 example:

 package main
 import (
     "net/http"
     "fmt"

    "github.com/lintanghui/parse"
 )
 func main(){
    type v struct {
        Data16   int8 `params:"aaa;Range(1,10)" default:"10"`
        Data32   int32
        Data64   int64    `params:"data64;Range(1,20)" default:"20"`
        Float32  float32  `params:"ccc"`
        String   string   `params:"sss" default:"-"`
        SliceInt []int64  `params:"iii"`
        SliceStr []string `params:"ttt"`
        Bool     bool     `params:"bbb"`
    }
    req, err := http.NewRequest("GET", "http://www.linth.top/x?aaa=11&data64=33&Data32=32&string=aaa&iii=1,2,3&ttt=a,b,c&bbb=true&ccc=1.2", nil)
    req.ParseForm()
    if err != nil {
        t.Log(err)
    }
    p := parse.New()
    var data = &v{}
    err = p.Bind(data, req.Form)
    fmt.Printf("%+v",data)
    // OUTPUT:
    // &{Data16:10 Data32:32 Data64:20 Float32:1.2 String: SliceInt:[1 2 3] SliceStr:[a b c] Bool:true}
 }

https://github.com/lintanghui/parse

1 个评论

https://github.com/gorilla/schema

要回复文章请先登录注册