1schema 2====== 3[![GoDoc](https://godoc.org/github.com/gorilla/schema?status.svg)](https://godoc.org/github.com/gorilla/schema) [![Build Status](https://travis-ci.org/gorilla/schema.png?branch=master)](https://travis-ci.org/gorilla/schema) 4[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/schema/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/schema?badge) 5 6 7Package gorilla/schema converts structs to and from form values. 8 9## Example 10 11Here's a quick example: we parse POST form values and then decode them into a struct: 12 13```go 14// Set a Decoder instance as a package global, because it caches 15// meta-data about structs, and an instance can be shared safely. 16var decoder = schema.NewDecoder() 17 18type Person struct { 19 Name string 20 Phone string 21} 22 23func MyHandler(w http.ResponseWriter, r *http.Request) { 24 err := r.ParseForm() 25 if err != nil { 26 // Handle error 27 } 28 29 var person Person 30 31 // r.PostForm is a map of our POST form values 32 err = decoder.Decode(&person, r.PostForm) 33 if err != nil { 34 // Handle error 35 } 36 37 // Do something with person.Name or person.Phone 38} 39``` 40 41Conversely, contents of a struct can be encoded into form values. Here's a variant of the previous example using the Encoder: 42 43```go 44var encoder = schema.NewEncoder() 45 46func MyHttpRequest() { 47 person := Person{"Jane Doe", "555-5555"} 48 form := url.Values{} 49 50 err := encoder.Encode(person, form) 51 52 if err != nil { 53 // Handle error 54 } 55 56 // Use form values, for example, with an http client 57 client := new(http.Client) 58 res, err := client.PostForm("http://my-api.test", form) 59} 60 61``` 62 63To define custom names for fields, use a struct tag "schema". To not populate certain fields, use a dash for the name and it will be ignored: 64 65```go 66type Person struct { 67 Name string `schema:"name,required"` // custom name, must be supplied 68 Phone string `schema:"phone"` // custom name 69 Admin bool `schema:"-"` // this field is never set 70} 71``` 72 73The supported field types in the struct are: 74 75* bool 76* float variants (float32, float64) 77* int variants (int, int8, int16, int32, int64) 78* string 79* uint variants (uint, uint8, uint16, uint32, uint64) 80* struct 81* a pointer to one of the above types 82* a slice or a pointer to a slice of one of the above types 83 84Unsupported types are simply ignored, however custom types can be registered to be converted. 85 86More examples are available on the Gorilla website: https://www.gorillatoolkit.org/pkg/schema 87 88## License 89 90BSD licensed. See the LICENSE file for details. 91