在我有点背景之前,我很擅长编程语言.我正在运行Win 7,最新的Windows程序包安装程序.我不擅长编码,但我确实喜欢学习一门新语言的挑战.我想开始学习Erlang但是根据youtube上的GO I/O视频发现它非常有趣.
我在GO中捕获POST表单值时遇到问题.我昨天花了三个小时才开始在浏览器中打印POST表单值并且失败了.我不知道我做错了什么,有人能指出我正确的方向吗?我可以用C#,PHP,VB,ASP,Rails等其他语言轻松完成这项工作.我搜索了整个interweb并且没有找到工作样本.以下是我的示例代码.
这是Index.html页面
{{ 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 }}
Run Code Online (Sandbox Code Playgroud)
这是基页
<!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>
Run Code Online (Sandbox Code Playgroud)
现在一些代码
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)
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
PS:在stackoverflow中的每行代码之前添加四个空格非常繁琐,尤其是在复制粘贴时.没有发现它非常用户友好或有更简单的方法吗?
在从请求中读取值之前写入 ResponseWriter(通过调用 Execute)会将其清除。
如果您使用此请求处理程序,您可以看到它的实际效果:
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"))
}
}
Run Code Online (Sandbox Code Playgroud)
这将在之前和之后打印出来。然而,在这种情况下:
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"))
}
}
Run Code Online (Sandbox Code Playgroud)
之后的值将为空。
归档时间: |
|
查看次数: |
2715 次 |
最近记录: |