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

huangapple go评论82阅读模式
英文:

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.

  1. 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
}
  1. 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.ObjectIDstring。(见下面的示例)

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
}

huangapple
  • 本文由 发表于 2022年7月19日 15:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73033098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定