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

Ama*_*ari 1 struct go

我有以下结构:

type Record struct {
  Id     string   `json:"id"`
  ApiKey string   `json:"apiKey"`
  Body   []string `json:"body"`
  Type   string   `json:"type"`
}
Run Code Online (Sandbox Code Playgroud)

这是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
  }
Run Code Online (Sandbox Code Playgroud)

在检查ApiKey是否等于提供的之后apiKey,我想删除ApiKeyfrom record,但不幸的是,这是不可能的delete.

谢谢.

Swi*_*ftD 9

在运行时无法实际编辑golang类型(例如结构).不幸的是,您还没有通过"删除"APIKey字段来解释您希望实现的目标.

一般方法是:

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

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

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