如何Golang检索表数据(如数组)? [英] How to retrieve Form data (as array) in Golang?

查看:275
本文介绍了如何Golang检索表数据(如数组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个PHP开发。但目前移动到Golang ...我试图从表中检索数据(Post方法):

 <! - 一个非常简单的形式 - >
<窗​​体类=行动=/联系的方法=后>
  <输入类型=文本名称=联系[名]VALUE =东西>
  <输入类型=文本名称=联系[电子邮件]VALUE =其他>
  < textarea的名字=联系[留言]>作为这个消息< / textarea的>
  <按钮式=提交>提交< /按钮>
< /表及GT;

在PHP中我会简单的用它来获取数据:

 < PHP
   的print_r($ _ POST [联系])
?>
//输出会是这样的:
排列

    [名称] =>某物
    [电子邮件] =>其他
    [消息] =>对于此消息

但在去...任我得到一个由一个或整个事情,但没有联系[]数组只能作为PHP这样

我想到了2解决方案:

1)获取一个接一个:

  // R:= * http.Request
错误:= r.ParseForm()如果犯错!= {为零
    w.Write([]字节(err.Error()))
    返回
}联系人:=使得(图[字符串]字符串)联系[名称] = r.PostFormValue(联系[名])
联系[电子邮件] = r.PostFormValue(联系[电子邮件])
联系[消息] = r.PostFormValue(联系[留言])fmt.Println(接触)//输出
图[产品名称:东西电邮:否则信息:此消息]

请注意,地图键全:联系[名]...

2)量程整个地图 r.Form 和解析|取得以preFIX这些值
联系[,然后替换联系[和]与空字符串
这样我就可以得到数组形式,重点只有这样的PHP示例

我就对这的相关工作由我自己,但...范围在整个形式可能不是一个好主意(?)

  // ContactPost过程用户发送表单
FUNC ContactPost(W http.ResponseWriter,R * http.Request,PS httprouter.Params){
    错误:= r.ParseForm()    如果犯错!= {为零
        w.Write([]字节(err.Error()))
        返回
    }    联系人:=使得(图[字符串]字符串)   对于i:=范围r.Form {
       如果strings.Has preFIX(我,联系[){
           RP:= strings.NewReplacer(联系[,,],)
           联系[rp.Replace(I)] = r.Form.Get(I)
       }
   }    w.Write([]字节(fmt.Sprint(接触)))
}
//输出
图[产品名称:东西电邮:否则信息:此消息]

这两种解决方案给我相同的输出...但在第二个例子我不一定需要知道的联系[]

我知道......我可能只是忘记了形阵,并使用 NAME =电子邮件我的输入和检索一个接一个,但...我通过一些场景中,我用一个表格包含超过2数组中的数据,并与每个人做不同的事情,就像奥姆斯

问题1 :是否有一个更简单的方法,让我的数组形式,在Golang像PHP的实际地图确实

问题2 :我应该获取一个数据一(乏味的多,我可能会在某个时候改变表单数据并重新编译......)或者迭代整个事情,因为我已经在第二个例子完成的。

对不起,我英文不好...提前感谢!


解决方案

  

有没有一种更简单的方法,让我的数组形式,在Golang一个实际的地图,如PHP呢?


您可以使用的 http.Request 键入 PostForm 成员。这类型的 url.Values​​ - 实际上(当当)一图[字符串] []字符串是的,你可以把就是这样。你仍然需要调用 req.ParseForm()第一,虽然。

 如果错误:= req.ParseForm();呃!= {为零
    //处理错误
}关键,值:=范围req.PostForm {
    // [...]
}

注意 PostForm 是地图上的字符串的列表。这是因为从理论上讲,每场可能是present在POST身体多次。在 PostFormValue()方法,通过隐式返回的第一多值(的的意思是,当你的文章的身体&放大器处理这;富=酒吧和放大器;富=巴兹,那么 req.PostFormValue(富)总是返回)。

另外请注意, PostForm 永远不会包含的嵌套结构就像你从PHP使用。由于走的是静态类型,一个POST表单值会的总是的是字符串(名称)为 []字符串的映射(价值/秒)。

就个人而言,我不会用括号语法(接触[邮件] )在进入应用后域的名称;这是一个PHP特定构造,反正你已经注意到了,Go不支持很好。


  

我应该(尽可能多的繁琐,我可能在某个时候改变表单数据,并重新编译......)检索一个数据的一个或遍历整个事情,因为我在第二个例子已经做到了。


有可能是针对没有正确答案。如果你映射你的POST领域与静态字段的结构体,你就必须在某个时刻显式地映射他们(或使用的 反映 实现某种神奇的自动映射)。

I'm a PHP Dev. But currently moving to Golang... I'm trying to retrieve data from a Form (Post method):

<!-- A really SIMPLE form -->
<form class="" action="/Contact" method="post">
  <input type="text" name="Contact[Name]" value="Something">   
  <input type="text" name="Contact[Email]" value="Else">
  <textarea name="Contact[Message]">For this message</textarea>
  <button type="submit">Submit</button>
</form>

In PHP I would simple use this to get the data:

<?php 
   print_r($_POST["Contact"])
?>
// Output would be something like this:
Array
(
    [Name] => Something
    [Email] => Else
    [Message] => For this message
)

BUT in go... either I get one by one or the whole thing but not the Contact[] Array only such as PHP

I thought about 2 solutions:

1) Get one by one:

// r := *http.Request
err := r.ParseForm()

if err != nil {
    w.Write([]byte(err.Error()))
    return
}

contact := make(map[string]string)

contact["Name"] = r.PostFormValue("Contact[Name]")
contact["Email"] = r.PostFormValue("Contact[Email]")
contact["Message"] = r.PostFormValue("Contact[Message]")

fmt.Println(contact)

// Output
map[Name:Something Email:Else Message:For this Message]

Note that the map keys are the whole: "Contact[Name]"...

2) Range whole map r.Form and "parse|obtain" those values with Prefix "Contact[" and then replacing "Contact[" and "]" with empty string so I can get the Form array Key only such the PHP Example

I went for this work around by my own but... ranging over the whole form may not be a good idea (?)

// ContactPost process the form sent by the user
func ContactPost(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    err := r.ParseForm()

    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    contact := make(map[string]string)

   for i := range r.Form {
       if strings.HasPrefix(i, "Contact[") {
           rp := strings.NewReplacer("Contact[", "", "]", "")
           contact[rp.Replace(i)] = r.Form.Get(i)
       }
   }

    w.Write([]byte(fmt.Sprint(contact)))
}
//Output
map[Name:Something Email:Else Message:For this Message]

Both solutions give me the same output... But in the 2nd example I don't necessarily need to know the keys of "Contact[]"

I know... I may just forget about that "Form Array" and use name="Email" on my inputs and retrieve one by one but... I've passing through some scenarios where I use ONE form that contain more than 2 arrays of data and do different things with each one, like ORMs

Question 1: Is there a easier way to get my Form Array as an actual map in Golang like PHP does?

Question 2: Should I retrieve the data one by one (Tedious as much and I may change the Form data at some point and recompile...) or iterate the whole thing as I've done in the 2nd example.

Sorry for my bad English... Thanks in advance!

解决方案

Is there a easier way to get my Form Array as an actual map in Golang like PHP does?

You can use the PostForm member of the http.Request type. It is of type url.Values -- which is actually (ta-da) a map[string][]string, and you can treat is as such. You'll still need to call req.ParseForm() first, though.

if err := req.ParseForm(); err != nil {
    // handle error
}

for key, values := range req.PostForm {
    // [...]
}

Note that PostForm is a map of lists of strings. That's because in theory, each field could be present multiple times in the POST body. The PostFormValue() method handles this by implicitly returning the first of multiple values (meaning, when your POST body is &foo=bar&foo=baz, then req.PostFormValue("foo") will always return "bar").

Also note that PostForm will never contain nested structures like you are used from PHP. As Go is statically typed, a POST form value will always be a mapping of string (name) to []string (value/s).

Personally, I wouldn't use the bracket syntax (contact[email]) for POST field names in Go applications; that's a PHP specific construct, anyway and as you've already noticed, Go does not support it very well.

Should I retrieve the data one by one (Tedious as much and I may change the Form data at some point and recompile...) or iterate the whole thing as I've done in the 2nd example.

There's probably no correct answer for that. If you are mapping your POST fields to a struct with static fields, you'll have to explicitly map them at some point (or use reflect to implement some magical auto-mapping).

这篇关于如何Golang检索表数据(如数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆