Hi,
i have a question for all you golang ninjas!
In my api code i am using the MongoDB driver mgo. I initialize the mgo.Session and mgo.Database in the InitSession method in model/db.go.
I wrote a Datastore interface to distribute the database connection to all model methods that need db access. Now i have the following problem. My model methods cannot extend the type (db *mgo.Database) since it is no local type. Aliasing the mgo.Database type wouldn't help either since i need also access to the mgo.Database methods. I came up with an solution which feels dirty to me by wrapping the mgo.Database struct inside my own Database struct.
Is there a more elegant solution for this problem?
Here is the code fragment: https://gist.github.com/gdenn/24f787b2cbf5d51879ffb14036cd5e02
评论:
radovskyb:
What you are doing is fine from what I can see in that snippet.
It's actually a good practice to wrap your database types in your own types that implement interfaces as it makes it quite easy to swap out for different implementations if needed.
I'm not sure what other types of "extending" you need to do with your mongo database, but for that, it looks good.
Here is an example of something similar I wrote a while back (needs some work, was out of boredom):
- Repo Interface: https://github.com/radovskyb/services/blob/master/user/datastore/repo.go
- MySQL implementation: https://github.com/radovskyb/services/blob/master/user/datastore/mysql.go
- In memory implementation: https://github.com/radovskyb/services/blob/master/user/datastore/mock.go
Edit: I do however suggest separating concerns a little bit better. Rather than having a single Datastore
interface in a single models
package, it might be better to create a separate UserStore
which has it's own interface.
Otherwise your models
package might get quite cluttered in a big application.
dchapes:thanks radovskyb, i see your point for the interface seperation.
radovskyb:own types that inherit from interfaces
It's not helpful to misuse the word "inherit" here. Go does not have inheritance; it does have composition via embedding.
This is true and I should have said
implements interfaces
, but we are all human and make mistakes :PI edited it anyway because you are right even if we are being slightly pedantic about the point here lol!
