Wednesday, December 4, 2013

Part III: Let's catch the fish

Folks! Today I'm going to show you, how to submit the form and pass the necessary values through a custom handler.
package mycanteen
  
import(
 "net/http"
 "html/template"
 "strconv"
 "fmt"
)
  
// No main function. Go App Engine use the init-func
func init() {
    http.HandleFunc("/", root)
    http.HandleFunc("/admin", admin);
    http.HandleFunc("/save", save)
}
  
func root(w http.ResponseWriter, r *http.Request) {    
    // Here we will add the Userpanel, but not know 
}

/*********************ADMINPANEL HANDLER**************************/ 
func admin(w http.ResponseWriter, r *http.Request) {      
    // Execute the parsing. We pass the ResponseWriter and a second value, which should be fill the gaps at the template. 
    // We have no gaps, so we have nothing to fill in. 
    if err := adminPanelTemplate.Execute(w, ""); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}
/********************SAVE/PERSIST HANDLER************************/
func save(w http.ResponseWriter, r *http.Request) {    
    // You have to parse the form from our admin panel. It's mandatory!
    if err := r.ParseForm(); err != nil {
     fmt.Fprint(w,err) 
    }
    
    // Now we a readey to get the fish ;-)
    course := r.FormValue("course")
    name := r.FormValue("name")
    date := r.FormValue("date")
    // The form is string based, for later purpose we parse it to float
    price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
    
    // At this moment we cant save the values, hence we setup only this output to check the values. 
    fmt.Fprintf(w, "You \"saved\" successfully: Our first %s %s costs %v %s on %s", course,name,price,string(0x20AC),date)
    
}

// Parse the HTMLTemplate, despite it is not neccesary yet.
var adminPanelTemplate = template.Must(template.New("adminPanelHTML").Parse(adminPanelHTML))
  
// Here you define the HTML which will be parsed.
const adminPanelHTML= `
<html>
<head>
</head>
<body>
Name: Price: Date:
</body> </html> `
At the beginning we add our libaries strconv(String Converting) & fmt(Formatting).
Setting the new custom handler save, we are able to catch the request. Otherwise the app can't handle it.
Want not to explain the save-Function, because I write self-explaining comments. // Comments are helpful as usual!
Don't forget update the form action value.

That's all for today, stay tuned!

No comments:

Post a Comment