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

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

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。