doutuan8887 2018-03-12 17:36
浏览 78
已采纳

是否可以在运行时删除结构值的字段?

I have the following struct:

type Record struct {
  Id     string   `json:"id"`
  ApiKey string   `json:"apiKey"`
  Body   []string `json:"body"`
  Type   string   `json:"type"`
}

Which is a Blueprint of a dynamoDB table. And I need somehow, delete the ApiKey, after using to check if the user has access to the giving record. Explaining:

I have and endpoint in my API where the user can send a id to get a item, but he needs to have access to the ID and the ApiKey (I'm using Id (uuid) + ApiKey) to create unique items.

How I'm doing:

 func getExtraction(id string, apiKey string) (Record, error) {
    svc := dynamodb.New(cfg)

    req := svc.GetItemRequest(&dynamodb.GetItemInput{
      TableName: aws.String(awsEnv.Dynamo_Table),
      Key: map[string]dynamodb.AttributeValue{
        "id": {
          S: aws.String(id),
        },
      },
    })

    result, err := req.Send()
    if err != nil {
      return Record{}, err
    }

    record := Record{}
    err = dynamodbattribute.UnmarshalMap(result.Item, &record)
    if err != nil {
      return Record{}, err
    }

    if record.ApiKey != apiKey {
      return Record{}, fmt.Errorf("item %d not found", id)
    }
    // Delete ApiKey from record
    return record, nil
  }

After checking if the ApiKey is equal to the provided apiKey, I want to delete the ApiKey from record, but unfortunately that's not possible using delete.

Thank you.

  • 写回答

1条回答 默认 最新

  • drn61317 2018-03-12 18:04
    关注

    There is no way to actually edit a golang type (such as a struct) at runtime. Unfortunately you haven't really explained what you are hoping to achieve by "deleting" the APIKey field.

    General approaches would be:

    1. set the APIKey field to an empty string after inspection, if you dont want to display this field when empty set the json struct tag to omitempty (e.g `json:"apiKey,omitempty"`)

    2. set the APIKey field to never Marshal into JSON ( e.g ApiKey string `json:"-"`) and you will still be able to inspect it just wont display in JSON, you could take this further by adding a custom marshal / unmarshal function to handle this in one direction or in a context dependent way

    3. copy the data to a new struct, e.g type RecordNoAPI struct without the APIKey field and return that after you have inspected the original Record

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)