norwat
norwat

Reputation: 218

Sharing structs across multiple packages

Lets say we have a client server scenario, in this situation both the server and the client speak to each other using a common message structure. So, one use struct to define that message structure, something like this

type Message struct {
    SenderId int
    Content string
    AuthCode string
}

Now to avoid repeating yourself and having a Message structure in both the client package and server package, what is the GoWay to address this problem ?

Thanks!

Upvotes: 1

Views: 2756

Answers (1)

Soheil Hassas Yeganeh
Soheil Hassas Yeganeh

Reputation: 1379

There are three different approaches:

  1. Keeping both server and client in the same package, as does the http package.
  2. Creating separate packages (say message, common, types, ...) and adding your shared structures there, as does etcd
  3. Putting them in the server package and importing that in the client package. For example, the x/net/websocket package imports net/http.

It's really a matter of personal taste.

Upvotes: 10

Related Questions