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

6

我有以下结构体:

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 是不可能的。

谢谢您。


2
你不能在运行时修改结构体的类型定义。结构体类型的值将始终具有结构体类型定义的所有字段。 - Adrian
你只想用空字符串将其清空吗? - RayfenWindspear
3
可能是与从结构中删除字段或在JSON响应中隐藏它们相关的重复问题。 - kostix
2个回答

27

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

一般的方法可能包括:

  1. 检查之后将APIKey字段设置为空字符串。如果您不想在该字段为空时显示它,则将json结构标记设置为omitempty(例如`json:“apiKey,omitempty”`)

  2. 将APIKey字段设置为永远不会编组成JSON(例如ApiKey字符串 `json: "-"`),您仍然可以检查它,但在JSON中不会显示,您可以进一步添加自定义Marshal / Unmarshal函数来处理这个问题,以单向或上下文相关方式进行处理

  3. 将数据复制到新的结构中,例如没有APIKey字段的RecordNoAPI结构,并在检查原始记录后返回它


1
  1. 创建了没有 "ApiKey" 的 RecordShort 结构
  2. 将 Record 进行编组
  3. 将 Record 反编组为 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接