【问题标题】:Martini binding doesn't appear to be working马提尼酒装订似乎不起作用
【发布时间】:2014-08-26 18:54:52
【问题描述】:

我正在玩 Martini,但由于某种原因,我无法让 contrib 绑定​​包工作。

我的结构没有绑定值。我已将代码简化为最简单的形式,但它仍然不起作用。

谁能看出我做错了什么?

package main

import (
    "github.com/go-martini/martini"
    "github.com/martini-contrib/binding"
    "net/http"
)

var html string = `<form method="POST" enctype="application/x-www-form-urlencoded"><input name="un" type="text" /><input type="submit" value="Some button" /></form>`

type FormViewModel struct {
    Username string `form: "un"`
}

func main() {
    m := martini.Classic()

    m.Get("/", func(w http.ResponseWriter) {
        w.Header().Add("content-type", "text/html")
        w.Write([]byte(html))
    })

    m.Post("/", binding.Form(FormViewModel{}), func(vm FormViewModel) string {
        return "You entered: " + vm.Username
    })

    m.Run()
}

【问题讨论】:

    标签: binding go martini


    【解决方案1】:

    只是结构字段关联的标签定义中的解析问题。

    form:

    后面的空格需要去掉

    如果你把结构写成如下:

    type FormViewModel struct {
        Username string `form:"un"`   // No blank after form:
    }
    

    ...它应该工作得更好。

    Go 语言规范说:

    按照惯例,标签字符串是可选用空格分隔的键:“值”对的串联。每个键都是一个非空字符串,由除空格 (U+0020 ' ')、引号 (U+0022 '"') 和冒号 (U+003A ':') 以外的非控制字符组成。每个值都被引用使用 U+0022 '"' 字符和 Go 字符串文字语法。

    显然,the reflect package 中实现的解析器不允许冒号后面有空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多