Golang : Gorilla web tool kit schema example
This is an example on how to use Gorilla web tool kit Schema package. The Schema package is very useful in mapping data from Form into objects(struct).
Here you go!
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"net/http"
)
type Person struct {
Name string
Phone string
}
func GetFormDataHandler(w http.ResponseWriter, r *http.Request) {
html := `<h1>Contact : </h1>
// replace example.com to your machine domain name or localhost
<form action="http://example.com:8080/process_form_data" method="post">
<div>
<label>Name : </label>
<input type="text" name="name" id="name" >
</div>
<div>
<label>Phone : </label>
<input type="text" name="phone" id="phone" >
</div>
<div>
<input type="submit" value="Send">
</div>
</form>`
w.Write([]byte(fmt.Sprintf(html)))
}
func ReadFormDataHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
fmt.Println(err)
}
person := new(Person)
decoder := schema.NewDecoder()
err = decoder.Decode(person, r.PostForm)
if err != nil {
fmt.Println(err)
}
fmt.Println(person)
w.Write([]byte(fmt.Sprintf("Name is %v \n", person.Name)))
w.Write([]byte(fmt.Sprintf("Phone is %v \n", person.Phone)))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", GetFormDataHandler)
mx.HandleFunc("/process_form_data", ReadFormDataHandler)
http.ListenAndServe(":8080", mx)
}
Run the code and point your browser to the main page i.e localhost:8080, key in the data and press the "Send" button.
Reference :
See also : Golang : Gorilla mux routing example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.2k Golang : Missing Bazaar command
+5.2k Golang : Detect words using using consecutive letters in a given string
+6.7k Golang : How to fix html/template : "somefile" is undefined error?
+5.5k Golang : Compound interest over time example
+6.8k Golang : Not able to grep log.Println() output
+9.1k Golang : ffmpeg with os/exec.Command() returns non-zero status
+10.1k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+8.7k Golang : Generate EAN barcode
+23.8k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+8.3k Golang : Accept any number of function arguments with three dots(...)
+16.6k Golang : Covert map/slice/array to JSON or XML format
+9.1k Golang : Get all countries currencies code in JSON format