Search code examples
gorpc

How to deal with go RPC calling with an array as its return value?


I want to export my service as an RPC service and my local method is to get all users(struct type) from db such as follows,

func GetUsers() ([]model.User) {
    // business logic
}

Now I wrapped the method as the RPC patterns as follows,

func (api *API) RpcGetUsers(_, reply []*model.User) error {
    reply = dal.GetUsers()
    return nil
}

But When I ran the function an panic occurred. It mentioned that

"reply type of method "RpcGetUsers" is not a pointer: "[]*model.User""

How can I solve this issue?


Solution

  • RPC documentation says the method must look like:

    func (t *T) MethodName(argType T1, replyType *T2) error
    

    So you need a request and a reply type. You can do something like this:

    type Empty struct{}
    type Users struct {
       Users []model.User
    }
    
    func (api *API) RpcGetUsers(_ *Empty, reply *Users) error {
    ...
    }