英文:
How to share slightly different structs between two go apps?
问题
我在我的Go项目中遇到了一个重要的架构问题。
1)我有一个使用来自MongoDB数据库的结构的API。这意味着我使用database.ObjectID
数据类型来存储我的ID。例如,这是我如何在API中存储一个用户:
type User struct {
Id primitive.ObjectId `bson:"_id,omitempty"`
Username string
Tag int
}
2)前端应用程序也是用Go编写的,并且使用相同的结构,因为它显然是从API获取数据的。但是,对于前端应用程序来说,使用primitive.ObjectID
数据类型并不是很方便:转换为字符串不是自动的,而且操作起来有点困难。因此,从前端应用程序的角度来看,数据结构更可能是这样的:
type User struct {
Id string
Username string
Tag int
}
现在,为了不重复太多代码,我想通过创建一个第三方模块来在两个项目之间重用这些结构,而不必写两次(一次使用string
,另一次使用primitive.ObjectId
)。
我该如何做?
英文:
I'm facing a big architecture issue in my go project.
- I have an API that uses structures that come from a MongoDB databases. That means I'm using the
database.ObjectID
data type in order to store my IDs. For example, here is how I would store an user in the API :
type User struct {
Id primitive.ObjectId `bson:"_id,omitempty"`
Username string
Tag int
}
- The front app is also made in go and uses the same structures because it obviously takes its data from the API. BUT it's not very convenient for the front app to use this
primitive.ObjectID
data type : the parsing to string is not automatic and it's a bit difficult to manipulate. So from the app front point of view, the data structure would more likely look like this :
type User struct {
Id string
Username string
Tag int
}
Now in order not to repeat too much code, i would like to re-use those structures from one project to the other with a third party module i would create, without having to write them all twice (one version with string
, the other with primitive.ObjectId
).
How can I do ?
答案1
得分: 1
创建一个新的ID
类型,它等于interface{}
。然后在需要时使用这个ID
类型,将其转换为primitive.ObjectID
或string
。(见下面的示例)
type User struct {
ID ID `bson:"_id"`
}
type ID = interface{}
func main() {
u := User{
ID: primitive.NewObjectID(),
}
oid := u.ID.(primitive.ObjectID) // 转换为"primitive.ObjectID"
fmt.Println(reflect.TypeOf(oid)) // primitive.ObjectID
}
英文:
Create a new ID
type that is equal to interface{}
. Then use this ID
type, casting to primitive.ObjectID
or string
when needed. (See example below)
type User struct {
ID ID `bson:"_id"`
}
type ID = interface{}
func main() {
u := User{
ID: primitive.NewObjectID(),
}
oid := u.ID.(primitive.ObjectID) // Cast to "primitive.ObjectID"
fmt.Println(reflect.TypeOf(oid)) // primitive.ObjectID
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论