Details
Description
I'm having problems when I try to save a struct with a interface property
package main
|
|
import (
|
"context"
|
"log"
|
"time"
|
)
|
|
const MAX_INSERT_TIMEOUT = time.Second * 10
|
|
type Scannable interface {
|
GetValue() int
|
IsOpen() bool
|
}
|
|
type Port struct {
|
Value int `bson:"value"`
|
Open bool `bson:"open"`
|
}
|
|
type MongoDBPort struct {
|
Port `bson:",inline"`
|
}
|
|
type Scanner struct {
|
Value string `bson:"value"`
|
Scannables []Scannable `bson:"scannable"`
|
Parallelism int `bson:"-"`
|
}
|
|
func NewPort(n int) Scannable {
|
if n == 27017 {
|
return &MongoDBPort{
|
Port{
|
Value: n,
|
},
|
}
|
}
|
|
return &Port{
|
Value: n,
|
}
|
}
|
|
func (p Port) IsOpen() bool {
|
return p.Open
|
}
|
|
func (p Port) GetValue() int {
|
return p.Value
|
}
|
|
func (s *Scanner) Save(ctx context.Context) {
|
var err error
|
|
db := Get("issues")
|
|
col := db.Collection("scanners")
|
|
ctxt, cancel := context.WithTimeout(ctx, MAX_INSERT_TIMEOUT)
|
defer cancel()
|
|
_, err = col.InsertOne(ctxt, s)
|
|
if err != nil {
|
log.Printf("Error on insert. %s", err.Error())
|
return
|
}
|
|
log.Println("Saved!")
|
}
|
This is the output when I try to save a Scanner:
Error on insert. no encoder found for main.Scannable |
I found a solution. But, in my opinion, is not the best solution. I used "gopkg.in/mgo.v2/bson" package for marshalling the object and It is working fine. I tried with "go.mongodb.org/mongo-driver/bson" package but the error persist.
o, err := bson.Marshal(s)
|
|
if err != nil {
|
log.Printf("Error on marshal. %s", err.Error())
|
return
|
}
|
|
_, err = col.InsertOne(ctxt, o)
|