【发布时间】:2012-09-27 00:31:18
【问题描述】:
在我有点背景之前,我对编程语言还是很陌生。我在 Win 7 上运行 go,Windows 的最新 go 包安装程序。我不擅长编码,但我确实喜欢学习一门新语言的挑战。我想开始学习 Erlang,但根据 youtube 上的 GO I/O 视频发现 go 非常有趣。
我在 GO 中捕获 POST 表单值时遇到问题。我昨天花了三个小时在浏览器中打印一个 POST 表单值,结果惨遭失败。我不知道我做错了什么,谁能指出我正确的方向?我可以用 C#、PHP、VB、ASP、Rails 等其他语言轻松地做到这一点。我搜索了整个互联网,但没有找到工作示例。下面是我的示例代码。
这里是 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 }}
这是基本页面
<!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>
现在有一些 go 代码
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)
}
谢谢!
PS:在 stackoverflow 的每一行代码之前添加四个空格非常繁琐,尤其是在复制粘贴时。觉得它不是很人性化还是有更简单的方法?
【问题讨论】:
-
至于“四”空格..工具栏中有一个小按钮可以缩进代码,虽然你刚刚发现不是很直观。
-
您希望它在哪里打印出来?打印完所有 html 后,您拥有的代码会将其发送到浏览器页面。
-
是的,我希望它在没有发生的浏览器中呈现。抱歉没有使用正确的术语。我现在已经更正了。
-
几点:go1需要更新到
"net/http"。另外,您应该检查是否有从http.ListenAndServe("localhost:81", nil)返回的错误。另外,你需要删除strings..它没有被使用。
标签: go