2017-10-30 12 views
1

私はHTTPフォーム(ユーザー名、パスワード)の値を読み取る必要がある単純なWebアプリケーションをGoに書いています。しかし、印刷すると値が空であることがわかりました。 len(r.Form)len(r.Form["password"])はともに0を返します。はフィールドを読み取ろうとする前にアプリケーションで呼び出されていますが、私はリクエストを送信するために郵便番号を使用しています。 LinuxとmacOSの両方でテストされています。HTTPフォーム解析の実行 - 空のスライス/空の値を返しますか?

これをテストするためのコードは、Astaxie golang Webチュートリアルのコード例です。私はPostman requestを付けました。これまでのように見えます。

package main 

import (
    "fmt" 
    "html/template" 
    "log" 
    "net/http" 
    "strings" 
    "time" 
) 

func sayhelloName(w http.ResponseWriter, r *http.Request) { 
    r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) 
    // attention: If you do not call ParseForm method, the following data can not be obtained form 
    fmt.Println(r.Form) // print information on server side. 
    fmt.Println("path", r.URL.Path) 
    fmt.Println("scheme", r.URL.Scheme) 
    fmt.Println(r.Form["url_long"]) 
    for k, v := range r.Form { 
     fmt.Println("key:", k) 
     fmt.Println("val:", strings.Join(v, "")) 
    } 
    fmt.Fprintf(w, "Hello astaxie!") // write data to response 
} 

func login(w http.ResponseWriter, r *http.Request) { 
    fmt.Println("method:", r.Method) //get request method 
    if r.Method == "GET" { 
     t, _ := template.ParseFiles("login.gtpl") 
     t.Execute(w, nil) 
    } else { 
     r.ParseForm() 
     time.Sleep(3 * time.Second) 
     // logic part of log in 
     fmt.Println("username:", len(r.Form)) 
     fmt.Println("password:", len(r.Form["password"])) 
    } 

} 

func main() { 
    http.HandleFunc("/", sayhelloName) // setting router rule 
    http.HandleFunc("/login", login) 
    err := http.ListenAndServe(":9090", nil) // setting listening port 
    if err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

次に何をするかについてのご意見はありますか?

ありがとうございます!

答えて

4

は、それが他のHTTPメソッドの場合x-www-form-urlencoded

でない限りdocsに応じて体が解析されませんr.ParseForm()にあるのでform-dataからx-www-form-urlencoded

にあなたの郵便配達の要求にコンテンツタイプを変更してみてくださいまたはContent-Typeが application/x-www-form-urlencodedでない場合、要求本体は読み取られず、 r.PostFormは非ゼロの空の値に初期化されます。

0

私はその後request.FormValue(「例」)でフォームデータを読み込むあなたの最初のチェックコンテンツタイプを提案するフォームを使用する場合は、必ずキーがマップ内で有効かそうでないと、そうでない場合には、ランタイムを作るのですチェックエラー。

func login(w http.ResponseWriter, r *http.Request) { 
    fmt.Println("method:", r.Method) //get request method 
    if r.Method == "GET" { 
     t, _ := template.ParseFiles("login.gtpl") 
     t.Execute(w, nil) 
    } else { 
     fmt.Println("username:", r.FormValue("username")) 
     fmt.Println("password:", r.FormValue("password")) 
    } 

} 
関連する問題