Before I being a bit of background, I am very new to go programming language. I am running go on Win 7, latest go package installer for windows. I'm not good at coding but I do like some challenge of learning a new language. I wanted to start learn Erlang but found go very interesting based on the GO I/O videos in youtube.
I'm having problem with capturing POST form values in GO. I spend three hours yesterday to get go to print a POST form value in the browser and failed miserably. I don't know what I'm doing wrong, can anyone point me to the right direction? I can easily do this in another language like C#, PHP, VB, ASP, Rails etc. I have search the entire interweb and haven't found a working sample. Below is my sample code.
Here is Index.html page
{{ define "title" }}Homepage{{ end }}
{{ define "content" }}
<h1>My Homepage</h1>
<p>Hello, and welcome to my homepage!</p>
<form method="POST" action="/">
<p> Enter your name : <input type="text" name="username"> </P>
<p> <button>Go</button>
</form>
<br /><br />
{{ end }}
Here is the base page
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ template "title" . }}</title>
</head>
<body>
<section id="contents">
{{ template "content" . }}
</section>
<footer id="footer">
My homepage 2012 copy
</footer>
</body>
</html>
now some go code
package main
import (
"fmt"
"http"
"strings"
"html/template"
)
var index = template.Must(template.ParseFiles(
"templates/_base.html",
"templates/index.html",
))
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
index.Execute(w, nil)
if r.Method == "POST" {
a := r.FormValue("username")
fmt.Fprintf(w, "hi %s!",a); //<-- this variable does not rendered in the browser!!!
}
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
remPartOfURL := r.URL.Path[len("/hello/"):]
fmt.Fprintf(w, "Hello %s!", remPartOfURL)
}
func main() {
http.HandleFunc("/", GeneralHandler)
http.HandleFunc("/hello/", helloHandler)
http.ListenAndServe("localhost:81", nil)
}
Thanks!
PS: Very tedious to add four space before every line of code in stackoverflow especially when you are copy pasting. Didn't find it very user friendly or is there an easier way?
Writing to the ResponseWriter (by calling Execute) before reading the value from the request is clearing it out.
You can see this in action if you use this request handler:
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println("before",r.FormValue("username"))
index.Execute(w, nil)
if r.Method == "POST" {
fmt.Println("after",r.FormValue("username"))
}
}
This will print out before and after. However, in this case:
func GeneralHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.URL)
index.Execute(w, nil)
if r.Method == "POST" {
fmt.Println("after",r.FormValue("username"))
}
}
The after value will be blank.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With