2016-05-04 19 views
0

我是Golang的新手,並嘗試使用httprouter API獲取運行的基本http應用程序。儘管遵循in another StackOverflow question的建議,但我已經閱讀過張貼的表格數據。無法通過htprouter讀取Golang中的表單信息

這裏是我的代碼(減去不相干):

import (
    "fmt" 
    "net/http" 
    "github.com/julienschmidt/httprouter" 
) 


func main() { 
    r := httprouter.New() 
    r.POST("/sub", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { 
     r.Header.Set("content-type", "text/html") 
     err := r.ParseForm() 
     if err != nil { 
      fmt.Fprintf(w, "<h1>Error: %s</h1>\n", err) 
     } 
     fmt.Fprintf(w, "<h1>Submitted message!</h1>\n<p>-%s-</p>\n", r.PostFormValue("msg")) 
    }) 
    http.ListenAndServe("localhost:3000", r) 
} 

在輸出中,在那裏我看到-hello-,我剛纔看到--。當我檢查Firefox中的http請求時,在表單數據面板中,我看到msg:"hello",那麼爲什麼r.PostFormValue("msg")返回空字符串?

+2

也許你可以顯示實際的請求?順便說一句:你的'r.Header.Set(「content-type」,「text/html」)對請求是無意義的;它可能應該繼續迴應。 – Volker

回答

0

感謝Volker指出錯誤。當我註釋掉r.Header.Set("content-type", "text/html")行時,問題就解決了。也許是這個問題,或者IDE(LiteIDE)緩存舊版本的代碼時可能會遇到一些問題。無論如何,我現在可以讀取發佈的值。