【问题标题】:GO: How to POST data into datastore?GO:如何将数据发布到数据存储区?
【发布时间】:2013-06-18 08:23:16
【问题描述】:

1)通过模板方法渲染一个登录页面。 例如:这是 index.html

{{ define "title" }}Guestbook{{ end }}

    {{ define "content" }}
        <form action="/login" method="post">
          <div><label>UserName : </label><input name="username" type="text" /></div>
          <div><label>Password : </label><input name="password" type="password" /></div>
          <div><input type="submit" value="login"></div>
        </form>

    {{ end }}

2) hello.go 文件:

package main

import (
  "fmt"
  "html/template"
  "net/http"
)

var index = template.Must(template.ParseFiles(
  "templates/base.html",
  "templates/index.html",
))
type UserLogin struct{
    UserName string
    PassWord string
}


func handler(w http.ResponseWriter, r *http.Request) {  
    index.Execute(w, nil)    
}



/*func login(w http.ResponseWriter, r *http.Request) {  
        remPartOfURL := r.URL.Path[len("/login/"):] 
        if r.Method == "POST" {
           fmt.Fprintf(w, "after",r.FormValue("username"))       
        }   
        fmt.Fprintf(w, "Hello %s!", remPartOfURL)
    }*/
    func login(w http.ResponseWriter, r *http.Request) {    
        fmt.Fprint(w, "login : ", "\n")
    remPartOfURL := r.URL.Path[len("/login/"):]     
    if r.Method == "POST" {         
        g := UserLogin{
            UserName: r.FormValue("username"),
            PassWord: r.FormValue("password"),
        }
        fmt.Fprint(w, "&g : ", &g,"\n")  
    } 
    fmt.Fprintf(w, "Hello %s!", remPartOfURL)   
   }


func init() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/login/", login)
}

问题:点击登录按钮后:&g 应该打印用户名和密码值,但它显示为空:&g : &{ } 可以做什么?

【问题讨论】:

  • 更改问题和代码不好,失去焦点!将其更改为:fmt.Fprint(w, "%#v : ", g,"\n")

标签: google-app-engine go


【解决方案1】:

您可以尝试的一件事是将fmt.Fprintf 语句替换为http.Error 语句。

例如替换:

fmt.Fprintf(w, "after",r.FormValue("username"))

与:

http.Error(w, fmt.Sprintf("after %s", r.FormValue("username")), http.StatusOK)

您直接写信给http.ResponseWriter,这可能会导致问题。

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2017-03-14
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多