具有不同成分的多个结构

I have a problem that I am not sure how to solve in Go. I need to make a client that talks to a json based api.

So I thought that I would use composition to build the struct similar to below.

type (
    BaseData struct {
        CommonFields string
    }

    Data struct {
        BaseData
        Result string
    }
)

Now I would send the Data struct to the api and unmarshal the response to the results, all good so far.

Now the issue is that I have different requests to send that require a different "results" composition and therefore would need to have many definitions of the Data struct in the same package, which is no good.

I am struggling to see how this should be done. Any pointers in a direction will great.

Do not create a model structure that mirrors or imitates the API you want to use. Design your model in a way that makes sense to your program, following DDD principles at a high conceptual level, and SOLID principles at implementation level, for example.

Most probably:

  • You don't need all the features of the foreign API. By adhering too much to their structures, you will implement a lot of boilerplate that serves no purpose of its own in your program.
  • You don't want your program to break down due to minor changes in the foreign API.

Create a layer in your program for communicating with the foreign API, and make the rest of your program depend on this layer, never directly on the foreign API. This way, if something changes in the API, you just need to change the communication layer, the rest of the program can continue working unaffected.

In this communication layer, use whatever structures needed to talk to the API. Do not use any structures not needed. And convert these structures to the structures used within the rest of your program. This may involve a lot of manual copying that might not seem pretty at first, but it's the way to protect your program from external changes.