title: Serializing Models in Golang
body: <p>I'm trying to separate my code into models and serializers with the idea that there be defined serializers that handles all json responsibilities, i.e. separation of concerns.  I also want to be able to call a model object <code>obj.Serialize()</code> to get the serializer struct obj that I can then marshal.  Therefore, I've come up with the following design.  To avoid circular import I had to use interfaces in my serializers which leads to using getters in my models.  I've read that getters/setters aren't idiomatic go code and I would prefer not to have "boilerplate" getter code all over my models.  Is there a better solution to what I want to accomplish, keeping in mind I want separation of concerns and <code>obj.Serialize()</code>?</p>
  
  <pre><code>src/
      models/
          a.go
      serializers/
          a.go
  </code></pre>
  
  <p><code>models/a.go</code></p>
  
  <pre><code>import "../serializers"
  
  type A struct {
    name string
    age int // do not marshal me
  }
  
  func (a *A) Name() string {
    return a.name
  }
  
  // Serialize converts A to ASerializer
  func (a *A) Serialize() interface{} {
      s := serializers.ASerializer{}
      s.SetAttrs(a)
      return s
  }
  </code></pre>
  
  <p><code>serializers/a.go</code></p>
  
  <pre><code>// AInterface used to get Post attributes
  type AInterface interface {
    Name() string
  }
  
  // ASerializer holds json fields and values
  type ASerializer struct {
    Name `json:"full_name"`
  }
  
  // SetAttrs sets attributes for PostSerializer
  func (s *ASerializer) SetAttrs(a AInterface) {
    s.Name = a.Name()
  }
  </code></pre>