Search code examples
gojson-apigoogle-json-api

How to represent OnePayload and ManyPayload using a common interface


https://github.com/google/jsonapi/blob/master/node.go

The structs OnePayload and ManyPayload, in the link above, have common fields:

Data
Included
Links
Meta

I want to write a method which takes either OnePayload or ManyPayload as an argument and assign values to Links and Meta as follows:

func DoSomething(payload interface{}) {
    ...
    payload.Links = links
    payload.Meta = meta
}

But I get the following error:

payload.Links undefined (type interface{} has no field or method Links)
payload.Meta undefined (type interface{} has no field or method Meta)

Could you advise how to represent OnePayload and ManyPayload using a common interface please?


Solution

  • You can use reflection:

    func main() {
        op := OnePayload{}
        DoSomething(&op)
        fmt.Print(op)
    }
    
    func DoSomething(payload interface{}) {
        exampleLink := Links{}
        link := reflect.New(reflect.TypeOf(exampleLink))
        link.Elem().Set(reflect.ValueOf(exampleLink))
    
        reflect.ValueOf(payload).Elem().FieldByName("Links").Set(link)
    
    }