简体   繁体   English

如何在两个 Go 应用程序之间共享略有不同的结构?

[英]How to share slightly different structs between two go apps?

I'm facing a big architecture issue in my go project.我在我的 Go 项目中面临一个很大的架构问题。

  1. I have an API that uses structures that come from a MongoDB databases.我有一个使用来自 MongoDB 数据库的结构的 API。 That means I'm using the database.ObjectID data type in order to store my IDs.这意味着我正在使用database.ObjectID数据类型来存储我的 ID。 For example, here is how I would store an user in the API :例如,这是我在 API 中存储用户的方式:
type User struct {
    Id       primitive.ObjectId `bson:"_id,omitempty"`
    Username string
    Tag      int
}
  1. The front app is also made in go and uses the same structures because it obviously takes its data from the API.前面的应用程序也是用 go 制作的,并且使用相同的结构,因为它显然从 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.但是前端应用使用这个primitive.ObjectID数据类型不是很方便:解析为字符串不是自动的,操作起来有点困难。 So from the 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 ).现在为了不重复太多代码,我想通过我将创建的第三方模块将这些结构从一个项目重新使用到另一个项目,而不必将它们全部编写两次(一个版本带有string ,另一个带有primitive.ObjectId的.ObjectId )。

How can I do ?我能怎么做 ?

Create a new ID type that is equal to interface{} .创建一个等于interface{}的新ID类型。 Then use this ID type, casting to primitive.ObjectID or string when needed.然后使用此ID类型,在需要时转换为primitive.ObjectIDstring (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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM