[TOC] ## 安装 ``` go get -u github.com/gorilla/schema ``` ## 实例 ### simple demo ``` import "github.com/gorilla/schema" type Person struct { Name string `schema:"name"` // 支持schema标签 Phone string `schema:"-"` // - 表示此字段不进行绑定 } // 请求参数映射 values := map[string][]string{ "Name": {"Alex"}, "Phone": {"13399999999"}, } person := new(Person) decoder := schema.NewDecoder() decoder.Decode(person, values) ``` ### 结合 http ``` type Person struct { Name string `schema:"name,required"` // custom name, must be supplied Phone string `schema:"phone"` // custom name Admin bool `schema:"-"` // this field is never set } var Decoder = schema.NewDecoder() func MyHandler2(w http.ResponseWriter, r *http.Request) { r.ParseForm() var person Person e := Decoder.Decode(&person, r.PostForm) if e != nil { w.Write([]byte(e.Error())) } fmt.Printf("%+v\n", person) // {Name: Phone:123 Admin:false} w.Write([]byte("success")) } ``` ``` curl -X POST -d "name=cpj&phone=123" http://localhost:9090 -> success curl -X POST -d "phone=123" http://localhost:9090 -> name is empty ```