drvlf9739 2014-08-12 14:11
浏览 47

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

I'm trying to print a user's username that the user keyed into a form, using Fprintf:

GO code:

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)
    ...
}

According to this: http://golang.org/pkg/net/http/#Request.FormValue, FormValue returns a string, but Fprintf seems to require an interface type: http://golang.org/pkg/fmt/#Fprintf. How do I insert the correct value/type of "a" as in my code above? Or, is there a better way to do this?

  • 写回答

1条回答 默认 最新

  • dongqianwei6664 2014-11-14 09:28
    关注

    I am actually not sure if your code could work the way you intend it.

    Here's a slightly modifiede, working example:

    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)
        ...
    }
    

    Here is how it goes:

    1. The user makes a GET request to your /login page, and the loginHandler is called.
    2. In your loginhandler you are returning the login page html to the user's browser.
    3. Then the user enters it's data, and sends a POST request.
    4. In the loginhandler the differentiation between the types of requests make it possible to either render the form, or display the values posted.

    However, you should ALWAYS sanitize user data. The template/html does that for you, so please take a look. If you have other questions concerning the usage of that package, aks away!

    评论

报告相同问题?

悬赏问题

  • ¥20 C# TCP服务端,客户端退出后,不断有数据进来
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?