登录
首页 >  Golang >  Go问答

Echo 框架 Bind() html FormData

来源:stackoverflow

时间:2024-04-17 13:57:47 154浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Echo 框架 Bind() html FormData》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个类似 html 的表单:










我想用我的 structbind() 这种形式:

type userfrom struct {
  email string `json:"email" form:"email" query:"email"`
  password string `json:"password" form:"password" query:"password"`
  tags []tag
  free []string `json:"freeword[]" form:"freeword[]" query:"freeword[]"`
}
type tag struct {
  name string `json:"tags[name][]" form:"tags[name][]" query:"tags[name][]"`
  count string `json:"tags[count][]" form:"tags[count][]" query:"tags[count][]"`
}

但是如果我在 post 之后打印 bind() 的结果,我有:

u := new(userfrom)
if err = c.bind(u); err != nil {
  return
}
log.println(u)

这个糟糕的输出:

&{[email protected] pwdpwdpwd [] [word1 word2]}

userfrom 结构中的 tags []tag 行不起作用

如果您尝试将 tags []tag 更改为 tags tag 我有一个很好的最后一个条目

&{[email protected] pwdpwdpwd {tag3 3} [word1 word2]}

我想要这个输出:

&{[email protected] pwdpwdpwd [{tag1 1} {tag2 2} {tag3 3}] [word1 word2]}

你知道这个问题吗?

回显文档到 bind()


解决方案


有两个问题:

  1. 您没有正确指定表单输入名称,您的方式永远无法映射到您想要的任何语言的内容。在支持您想要的语言中,它将标记映射到两个字段(名称和计数)的结构,每个字段由一个数组组成。不是名称和计数的结构数组。名称应该像这样 tags[][name] 才能实现您想要的,请参见此处的示例:HTML Form: POST an array of objects
  2. 即使您按照上面正确指定了名称,它也无法在 echo 中工作,因为它依赖 http.request.form 来解析值,这实际上是 url.values ,而它又只是一个 map[字符串][]字符串。正如您所看到的,这不可能捕获您想要的结构。这是相关票证:https://github.com/golang/go/issues/29703

现在,仅仅因为 echo 不支持开箱即用的功能,并不意味着您不能这样做。您可以使用具有您需要的功能的第三方库进行绑定,例如 https://github.com/monoculum/formam

以下代码:

package main

import (
    "fmt"
    "net/url"

    "github.com/monoculum/formam"
)

type user struct {
    email,
    password string
    tags []struct {
        tag   string
        count int
    }
}

func main() {
    formdata := "[email protected]&password=secret&tags[0].tag=red&" + 
        "tags[0].count=1&tags[1].tag=blue"
    q, _ := url.parsequery(formdata)
    u := new(user)

    dec := formam.newdecoder(nil)
    if err := dec.decode(q, u); err != nil {
        fmt.println(err)
        return
    }

    fmt.println(u)
}

结果是你所需要的:

&{[email protected] secret [{red 1} {blue 0}]}

希望这有帮助!

理论要掌握,实操不能落!以上关于《Echo 框架 Bind() html FormData》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>