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 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题