Go中通用的解决方案

I want to make a useful library for JSON responses. In Java I've this already. I started now new with Go and have no idea how to transform my Java code. I've read that Go doesn't have anything like generics, but how can I solve my problem?

I'm talking about the following part of code:

@Data
public class ServiceResult<T extends Serializable> implements Serializable {

    private ServiceResultStatus status;
    private String type;
    private T content;
    private String hash;
    private String destination;
    private HashMap<String, Metadata> metadata = new HashMap<>();

...

The idea of service-result is to provide an structural pattern for RESTful web services. If you need more information, here is the link to my repo on Github: https://github.com/Viascom/service-result

A service-result looks at the end like this:

{
  "status": "successful",
  "type": "ch.viascom.example.models.response.GetTasksResponse",
  "content": [
    {
      "id": "3e99c7fb-0ed7-11e7-a7a5-0050569c3e5a",
      "name": "Example Task"
    }
  ],
  "hash": "7bf9c04d1e9f8fe7995e4b8beeac1a4c830e7ea",
  "destination": "ch.viascom.example.handler.TaskHandler",
  "metadata": {

  }
}

You can add the json-mapping directly to the structure definition and use the encoder, decoder to marshal and unmarshal it. It's all built in and easier than in other languages, imho.

type ServiceResponse struct {
    Value string`json:"nameInJsonResponse"`
}

here is a good example from the playground: https://play.golang.org/p/4L2wMVv7tW

For your particular case it should be something like this:

type ServiceResult struct {
    Status ServiceResultStatus`json:"status"`
    Type string`json:"type"`
    Hash string`json:"hash"`
    Destination string`json:"destination"`
    Metadata map[string]Metadata metadata`json:"metadata"`
}

type ExplizitServiceResult struct {
    ServiceResult
    Content SomeStruct`json:"content"`
}

https://play.golang.org/p/FFfiq6LxVt

If you don't want to derive every user struct from the ServiceResult you can define the content as interface{} so every struct can be inserted. I've updated my example for this. Maybe this is the easiest solution to your problem. https://play.golang.org/p/LNgreqrnnw