0

Here's a bit of a chicken and egg problem.

In a HTML template, a form, bson.ObjectId needs to be rendered with {{mytype.Id.Hex()}}

e.g.

<form method="post">
<input name="id" value="{{mytype.Id.Hex()}}>
</form>

In Go when defining a struct that is supposed to be parsed by gorilla/schema

type MyType struct {
    Id bson.ObjectId `bson:"_id,omitempty" schema:"id"`
}

when you call (from schema) decoder.Decode(instance_of_mytype, r.PostForm) it "throws" an error: schema: invalid path "id" since the format is just the string respresentation of bson.ObjectId and not an actual bson.ObjectId.

I wonder what I could do except filling the fields manually (r.FormValue()) to make it work.

Should I create an issue with gorilla/schema or mgo or should I just do it manually?

4

1 回答 1

0

您可以定义自己的基于字符串的类型,该类型包含值的十六进制表示,并在其上实现bson.Getterbson.Setter接口。Gorilla 将忽略这些接口并使用字符串值,而 bson 将忽略字符串值并使用接口。

这些方面的东西(未经测试的代码):

type hexId string

func (id hexId) GetBSON() (interface{}, error) {
        return bson.ObjectIdHex(string(id)), nil
}

func (id *hexId) SetBSON(raw bson.Raw) error {
        var objId bson.ObjectId
        err := raw.Unmarshal(&objId)
        if err != nil {
                return err
        }
        *id = hexId(objId.Hex())
        return nil
}
于 2015-02-11T12:16:09.013 回答