zeromicro / go-zero

A cloud-native Go microservices framework with cli tool for productivity.
https://go-zero.dev
MIT License
29.34k stars 3.96k forks source link

Why optional request parameter is not a pointer type generated by goctl api #4432

Open Tony7817 opened 1 month ago

Tony7817 commented 1 month ago

Describe the bug one block of my api is defined as:

    StarListRequest {
        Keyword string `json:"keyword,optional"`
        Page    int64  `json:"page"`
        Size    int64  `json:"size"`
    }

The keyword is optional. When I generate my code with goctl. The types.go is shown as blow:

type StarListRequest struct {
    Keyword string `json:"keyword,optional"`
    Page    int64  `json:"page"`
    Size    int64  `json:"size"`
}

Why the Keyword is not a pointer since it's optional? Let's see the protobuf's generation:

// .proto defination:
   message StarListRequest {
    int64 Page = 1;
    int64 Limit = 2;
    optional string Keyword = 3;

The code generated:

type StarListRequest struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    Page    int64   `protobuf:"varint,1,opt,name=Page,proto3" json:"Page,omitempty"`
    Limit   int64   `protobuf:"varint,2,opt,name=Limit,proto3" json:"Limit,omitempty"`
    Keyword *string `protobuf:"bytes,3,opt,name=Keyword,proto3,oneof" json:"Keyword,omitempty"`
}

See? It's a pointer. If api's generation of this field is not a pointer, it will be a trouble in api logic. since you have to do a if judgement to conver the filed to a pointer before you call rpc server.

  1. The error is

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Environments (please complete the following information):

More description Add any other context about the problem here.

Tony7817 commented 1 month ago

You have to mark it as a pointer in .api file.

    StarListRequest {
        Keyword *string `json:"keyword,optional"`
        Page    int64   `json:"page"`
        Size    int64   `json:"size"`
    }