我正在尝试使用 Fprintf 打印用户键入表单的用户名:
GO代码:
const logPage = `
<html>
<form action="/login" method="POST">
<label for="name">Username</label>
<input type="text" id="Username" name="name"></input>
...
</form>
</html>
`
const homePage = `
<html>
<h1>hi %s</h1>
</html>
`
func homehandler(w http.ResponseWriter, r *http.Request) {
a = r.FormValue("name")
fmt.Fprintf(w, homePage, a) ---> how do I insert the a value in the required interface{} form?
}
func main() {
http.HandleFunc("/home", homehandler)
...
}
根据这个:http://golang.org/pkg/net/http/#Request.FormValue , FormValue返回一个字符串,但是Fprintf好像需要一个接口(interface)类型:http://golang.org/pkg/fmt/#Fprintf .如何在上面的代码中插入正确的“a”值/类型?或者,是否有更好的方法来做到这一点?
最佳答案
我实际上不确定您的代码是否可以按您预期的方式工作。
这是一个稍微修改过的工作示例:
const logPage = `
<html>
<form action="/login" method="POST">
<label for="name">Username</label>
<input type="text" id="Username" name="name"></input>
...
</form>
</html>
`
const homePage = `
<html>
<h1>hi %s</h1>
</html>
`
func loginhandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprint(w, homePage)
} else if r.Method == "POST" {
// Here you can check the credentials
// or print the page you wanted to
// BUT please DON'T DO THIS
a = r.FormValue("name")
fmt.Fprint(w, logpage, a)
// DON'T DO THIS FOR THE SAKE OF YOUR USERS
}
}
func main() {
// http.HandleFunc("/home", homehandler) not needed
http.HandleFunc("/login", loginhandler)
...
}
事情是这样的:
- 用户向您的
/login
页面发出GET
请求,并调用loginHandler
。 - 在您的
loginhandler
中,您将登录页面 html 返回给用户的浏览器。 - 然后用户输入它的数据,并发送一个
POST
请求。 - 在登录处理程序中,请求类型之间的差异使得呈现表单或显示发布的值成为可能。
但是,您应该始终清理用户数据。 template/html
会为您做这些,所以请看一看。如果您对该软件包的使用有其他疑问,请留言!
关于GO:作为 Fprintf 参数传递的表单值类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266538/