How to create a reusable object that embeds other objects with different types?

I have many different models:

type objectModel struct {
	Title string `json:"title"`
	Body string `json:"body"`
}

// Many more models...

These models are used to create response objects that are returned to clients. All responses can contain various fields that depend on the context.

type objectResponse struct {
	OK bool `json:"ok"`
	Object *objectModel `json:"object"`
}

type objectListResponse struct {
	OK bool `json:"ok"`
	Objects []*objectModel `json:"objects"`
}

// Many more response types that are similar to these two examples.

Problem

What I want to have is a reusable response object that embeds all these different custom response objects objectResponse, objectListResponse and so on. In this case I wouldn’t need to define OK bool on every response object I have. I would use it like this: response.write(responseWriter), but that’s out of the scope of this question.

type response struct {
    OK bool `json:"ok"`
    CustomResponse
}

It should be possible with an interface, but I don’t know what common method all of the responses should implement.

Thanks in advance!

You could define something like

type ok struct {
	OK bool `json:"ok"`
}

And embed that in your responses like this:

type objectResponse struct {
	ok
	objectModel
}

Here’s an example: https://play.golang.org/p/tFc4qjYsT2B

You could also use json.NewEncoder(responseWriter).Encode(resp).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.