douyan6548 2015-08-14 01:48
浏览 41
已采纳

Golang将地图键设置为其值的变量

I need to go through an html forms input values and place them into an mysql datbase. Which I'm currently using r.Form to get a map. So that i don't have to use r.Form.Get("date") for each which works but when i try to put the values into a database. It compiles just fine but i get sql: converting argument #0's type: unsupported type []string, a slice after i click submit in the browser. I can get around this by doing

`date := strings.Join(m["date"], "")`

but doing that for 30+ values especially since some of the submited values will be created from previous database entries using html templates. If i have to change or add more later seems like there must be a more efficient way I've seen for key, val := range m {} but unfortunately I've only been doing this for about a week and i can't figure out how to keep the values and change the variable they get set to after each iteration. So that after

for key, val := range m {
x := m[key]
}

so that it will put out the equivalent

keyname := keyvalue

changing the keyname each time to be the same as the keyname in the map ie

date := 2015-8-13
time := 18:56:11

or if there's an easier way around this error then to create a varible for each one.

  • 写回答

1条回答 默认 最新

  • dongtanliefang8765 2015-08-14 02:29
    关注

    An HTML form can have multiple values for a single key. This is why the request form field is defined to be a map of string slices. The request Form is declared as

     Form url.Values
    

    and url.Values is declared as

      type Values map[string][]string
    

    You can access the first value for a key using:

       var value string
       if values := req.Form[key]; len(values) > 0 {
          value = values[0]
       }
    

    The url.Values Get helper method simplifies this code to:

       value := req.Form.Get(key)
    

    The http.Request FormValue helper method simplifies it a bit more:

      value := req.FormValue(key)
    

    You iterate through keys and values using:

      for key, values := range req.Form {
         for _, value := range values {
             fmt.Println(key, value)
         }
      }
    

    If you want to iterate over the first value for a key, then use this code:

     for key, values := range req.Form {
        if len(values) > 0 {
           value := values[0]
           fmt.Println(key, value)
        }
     }
    

    Before accessing req.Form, call req.ParseForm to parse the query string and request body.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号