【问题标题】:Is it possible to delete a field of a struct value at runtime?是否可以在运行时删除结构值的字段?
【发布时间】:2018-03-12 17:36:30
【问题描述】:

我有以下结构:

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

这是 dynamoDB 表的蓝图。我需要以某种方式删除 ApiKey,用于检查用户是否有权访问捐赠记录。解释:

我的 API 中有端点,用户可以发送id 来获取项目,但他需要访问 ID 和 ApiKey(我使用 Id (uuid) + ApiKey)来创建独特的物品。

我的表现如何:

 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
  }

在检查 ApiKey 是否等于提供的apiKey 后,我想从record 中删除ApiKey,但不幸的是,使用delete 是不可能的。

谢谢。

【问题讨论】:

标签: go struct


【解决方案1】:

没有办法在运行时实际编辑 golang 类型(例如结构)。不幸的是,您还没有真正解释您希望通过“删除” APIKey 字段来实现什么。

一般方法是:

  1. 检查后将APIKey字段设置为空字符串,如果您不想在空时显示该字段,请将json struct标签设置为omitempty(例如`json:"apiKey,omitempty"`)

  2. 将 APIKey 字段设置为从不编组为 JSON(例如 ApiKey 字符串 `json:"-"`),您仍然可以检查它,只是不会在 JSON 中显示,您可以通过添加自定义 marshal / unmarshal 函数以单向或上下文相关方式处理此问题

  3. 将数据复制到新结构中,例如键入不带 APIKey 字段的 RecordNoAPI 结构,并在检查原始记录后返回该结构

【讨论】:

    【解决方案2】:
    1. 创建了没有“ApiKey”的 RecordShort 结构
    2. 马歇尔唱片
    3. 将记录解组到 ShortRecord
    type RecordShot struct {
      Id     string   `json:"id"`
      Body   []string `json:"body"`
      Type   string   `json:"type"`
    }
        
    record,_:=json.Marshal(Record)
    json.Unmarshal([]byte(record), &RecordShot)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多