如何在Go(Golang)中将表单数据作为地图检索(例如PHP和Ruby) [英] How to retrieve form-data as map (like PHP and Ruby) in Go (Golang)

查看:89
本文介绍了如何在Go(Golang)中将表单数据作为地图检索(例如PHP和Ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP开发人员.但是目前正在转向Golang ...我正在尝试从Form(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>

在PHP中,我将简单地使用它来获取数据:

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
)

继续进行中...要么一一得到,要么一无所获,但不是诸如PHP之类的Contact []数组

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)一一获得:

// 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]

请注意,地图键是整个键:"Contact [Name]" ...

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

2)对整个地图r.Form进行范围调整,并使用前缀"解析"这些值 "Contact [",然后将"Contact ["和]"替换为空字符串 所以我只能像PHP Example这样获得Form数组键

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]

两个解决方案都给我相同的输出...但是在第二个示例中,我不一定需要知道"Contact []"的键

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

我知道...我可能只是忘了那个表单数组",而是在输入中使用name="Email"并逐个检索,但是...我已经经历了一些使用一个包含更多表单的情况超过2个数据数组,并且每个数据数组都做不同的事情,例如ORM

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

问题1 :是否有一种更简单的方法像PHP一样在Golang中将表单数组作为实际地图获取?

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

问题2 :我应该一个接一个地检索数据(非常乏味,我可能会在某个时候更改Form数据并重新编译...)还是迭代整个过程在第二个示例中完成.

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!

推荐答案

是否有更简单的方法像PHP一样在Golang中将表单数组获取为实际地图?

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

您可以使用http.Request类型的PostForm成员.它的类型为 url.Values -实际上(ta-da)是map[string][]string,并且您可以这样对待.不过,您仍然需要先致电req.ParseForm().

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 {
    // [...]
}

请注意,PostForm字符串列表 的映射.这是因为从理论上讲,每个字段都可以在POST正文中多次出现. PostFormValue()方法通过隐式返回多个值的 first (即,当您的POST正文为&foo=bar&foo=baz时,req.PostFormValue("foo")始终返回"bar")来处理此问题.

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").

还要注意,PostForm绝不会包含嵌套结构 ,就像您在PHP中所使用的那样.由于Go是静态类型的,因此POST表单值将始终是string(名称)到[]string(值/秒)的映射.

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).

就我个人而言,我不会在Go应用程序中对POST字段名称使用方括号语法(contact[email]);无论如何,这是一个特定于PHP的构造,并且您已经注意到,Go并不很好地支持它.

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.

我应该一个接一个地检索数据(尽可能多,而且我可能会在某个时候更改Form数据并重新编译...)还是像在第二个示例中所做的那样迭代整个过程.

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.

可能没有正确的答案.如果要将POST字段映射到具有静态字段的结构,则必须在某个时候显式映射它们(或使用 reflect 来实现一些神奇的自动映射).

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).

这篇关于如何在Go(Golang)中将表单数据作为地图检索(例如PHP和Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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