Given the following code: (reproduced here at play.golang.org.)
package main
import (
"encoding/json"
"fmt"
)
type User struct {
I needed to do something similar and tried your technical of the embedded interface and (no surprise) had the same issue.
I didn't want to have to alter all the possible structs that needed additional fields, but ultimately I compromised with this solution:
http://play.golang.org/p/asLFPx76jw
package main
import (
"encoding/json"
"fmt"
)
type HateoasFields struct {
Links []interface{} `json:"_links,omitempty"`
}
type User struct {
Id int `json:"id"`
Name string `json:"name"`
HateoasFields
}
type Session struct {
Id int `json:"id"`
UserId int `json:"userId"`
HateoasFields
}
func main() {
u := &User{Id: 123, Name: "James Dean"}
s := &Session{Id: 456, UserId: 123}
u.Links = []interface{}{fmt.Sprintf("http://user/%d", u.Id)}
s.Links = []interface{}{fmt.Sprintf("http://session/%d", s.Id)}
uBytes, _ := json.Marshal(u)
sBytes, _ := json.Marshal(s)
fmt.Println(string(uBytes))
fmt.Println(string(sBytes))
}
Which outputs:
{"id":123,"name":"James Dean","_links":["http://user/123"]}
{"id":456,"userId":123,"_links":["http://session/456"]}
Rather than embedding the original structs in a struct with the additional fields, I did the opposite.
When looking at your original code, I don't think this solution is that awesome. How is this better than adding the Links property to the original struct? But for my app needs it was the best thing.