Upon my last question, I want to convert a eunm(type alias) to string when I write it to mongodb with mgo. I know I need add rules for the bson Marshal/Unmarshal, but it's different with json which I need implement UnmarshalJSON
and MarshalJSON
, so what should I do with bson? The code below write a number to field S
, but I want the corresponding string
package main
import (
"encoding/json"
mgo "gopkg.in/mgo.v2"
)
type trxStatus int
type test struct {
S trxStatus
A string
}
const (
buySubmitted trxStatus = iota
buyFilled
sellSubmiited
sellFilled
finished
)
var ss = [...]string{"buySubmitted", "buyFilled", "sellSubmiited", "sellFilled", "Finished"}
// that's what I do for json
func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
var status string
json.Unmarshal(bytes, &status)
// unknown
for i, v := range ss {
if v == status {
tttt := trxStatus(i)
*s = tttt
break
}
}
return nil
}
func (s trxStatus) MarshalJSON() ([]byte, error) {
return json.Marshal(s.String())
}
func (s trxStatus) String() string {
if s < buySubmitted || s > finished {
return "Unknown"
}
return ss[s]
}
func main() {
db, _ := mgo.Dial("localhost")
s := test{S: buyFilled, A: "hello"}
c := db.DB("test").C("test")
c.Insert(s)
}