2016-11-12 97 views
0

將標準庫URL.Query()直接映射到結構將會非常棒。將URL.Query(切片圖)轉換爲結構golang

查詢()返回一個地圖等: 地圖[A:[AAAA] B:[BBBB] C:[CCCC]]

的結構是這樣的:

類型的事情結構{ 甲串 乙串 C字符串 }

*我不知道爲什麼URL.Query返回裏面強硬的數組元素的地圖。 (well ..我知道why但GET不可能有重複的參數)

+2

GET不太可能會有重複的參數。在這種情況下,它被轉換爲一段值。你看過gorilla.schema包嗎?我相信它可以完成這項工作。 –

+0

在我的情況下,我會很好,並希望在重複的情況下解僱一個例外。我看了一眼gorilla.schema,太棒了!謝謝。 – Custodio

回答

0

正如@ mh-cbon gorilla schema指出的是這裏的最終解決方案。

取而代之的是從URL屬性中獲取queryParams。

func handleRequest(w http.ResponseWriter, r *http.Request) { 
    queryString := r.URL.Query() 
    //...parsing the Values -> map[string][]string 
} 

大猩猩模式的方法是將r.PostForm運送到解碼功能。

func handleRequest(w http.ResponseWriter, r *http.Request) { 
    err := decoder.Decode(person, r.PostForm) 
    //...using reflect each struct's property can be called using 
    // the PostForm(url string, data url.Values) signature 

    fmt.Print(person.GoodJobGorilla) 
}