GO:作为 Fprintf 参数传递的表单值类型不正确

标签 go

我正在尝试使用 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)
    ...
}

事情是这样的:

  1. 用户向您的/login 页面发出GET 请求,并调用loginHandler
  2. 在您的 loginhandler 中,您将登录页面 html 返回给用户的浏览器。
  3. 然后用户输入它的数据,并发送一个POST请求。
  4. 在登录处理程序中,请求类型之间的差异使得呈现表单或显示发布的值成为可能。

但是,您应该始终清理用户数据。 template/html 会为您做这些,所以请看一看。如果您对该软件包的使用有其他疑问,请留言!

关于GO:作为 Fprintf 参数传递的表单值类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266538/

相关文章:

url - 如何使用 go 在 OAuth 中编写重定向 URL

time - Golang 扣除日期的特定时间

Golang 从不同包中的另一个 gloang 文件中删除对访问方法的循环依赖

html - GoLang - 带有 HTML 的 XmlPath 选择器

go - 如何在 Go 中将包分配给变量?

git - 您如何使用 bitbucket 服务器支持 'go get'?

postgresql - go-gorm postgres 方言 : managing structs for jsonb insert and find to properly use json tags

Golang gorm 有(就像在 Laravel 中)等效的方法?

xml - 在Golang中使用encoding/xml包制作soap xml

http - 如何在 golang 中使用 "422 Unprocessable Entity (WebDAV)"或任何其他自定义 http 状态代码