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

时间:2018-03-12 17:36:30

标签: go struct

我有以下结构:

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之后,我想从ApiKey删除record,但遗憾的是使用delete无法做到这一点。

谢谢。

2 个答案:

答案 0 :(得分:8)

在运行时无法实际编辑golang类型(例如结构)。不幸的是,你并没有真正解释你希望通过"删除" APIKey字段。

一般方法是:

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

  2. 将APIKey字段设置为永不Marshal为JSON(例如ApiKey字符串`json:" - "`),你仍然能够检查它不会以JSON显示,你可以通过添加自定义marshal / unmarshal函数来进一步解决这个问题,以便在一个方向或以上下文相关的方式处理这个问题

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

答案 1 :(得分:0)

  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)
相关问题