简体   繁体   English

在 golang 中与 []struct 交互

[英]Interact with []struct in golang

I have the code below:我有以下代码:

type AzStorageAccount struct {
Type     string `json:"type"`
Location string `json:"location"`
Tags     struct {
} `json:"tags"`
Properties struct {
    PrivateLinkServiceConnections []struct {
        Name       string `json:"name"`
        Properties struct {
            PrivateLinkServiceID              string `json:"privateLinkServiceId"`
            GroupIds                          string `json:"groupIds"`
            PrivateLinkServiceConnectionState struct {
                Status          string `json:"status"`
                Description     string `json:"description"`
                ActionsRequired string `json:"actionsRequired"`
            } `json:"privateLinkServiceConnectionState"`
        } `json:"properties"`
    } `json:"privateLinkServiceConnections"`
    ManualPrivateLinkServiceConnections []interface{} `json:"manualPrivateLinkServiceConnections"`
    Subnet                              struct {
        ID string `json:"id"`
    } `json:"subnet"`
    CustomDNSConfigs []interface{} `json:"customDnsConfigs"`
} `json:"properties"`

} }

But I'm having issues to assung the values to the variables inside PrivateLinkServiceConnections []struct {}但是我在将值分配给 PrivateLinkServiceConnections []struct {} 中的变量时遇到问题

At first I was using, but since I need to use []struct it does not work anymore.起初我正在使用,但由于我需要使用 []struct 它不再起作用。

storageAccount.Location = "eastus2"
    storageAccount.Type = "Microsoft.Network/privateEndpoints"
    storageAccount.Properties.PrivateLinkServiceConnections.Properties.PrivateLinkServiceId = "/subscriptions"
    storageAccount.Properties.PrivateLinkServiceConnections.Name = "priv-endpoint"
    storageAccount.Properties.PrivateLinkServiceConnections.Properties.GroupIds = "postgresqlServer"
    storageAccount.Properties.PrivateLinkServiceConnections.Properties.PrivateLinkServiceConnectionState.Status = "Approved"
    storageAccount.Properties.PrivateLinkServiceConnections.Properties.PrivateLinkServiceConnectionState.Description = "Auto-approved"
    storageAccount.Properties.PrivateLinkServiceConnections.Properties.PrivateLinkServiceConnectionState.ActionsRequired = "None"
    storageAccount.Properties.Subnet.Id = "/subscriptions/..."

marshaledStorageAccount, _ := json.Marshal(storageAccount)
utils.SendPut(endpoint, marshaledStorageAccount)    

How can assign values to the code below?如何为下面的代码赋值?

PrivateLinkServiceConnections []struct {
        Name       string `json:"name"`
        Properties struct {
            PrivateLinkServiceID              string `json:"privateLinkServiceId"`
            GroupIds                          string `json:"groupIds"`
            PrivateLinkServiceConnectionState struct {
                Status          string `json:"status"`
                Description     string `json:"description"`
                ActionsRequired string `json:"actionsRequired"`
            } `json:"privateLinkServiceConnectionState"`
        } `json:"properties"`
    } `json:"privateLinkServiceConnections"`

Thanks!谢谢!

The easiest and sane way to do this is by defining a new type:最简单、最明智的方法是定义一个新类型:

type PrivateLinkServiceConnections struct {
        Name       string `json:"name"`
       ...   
}

Properties struct {
    Connections []PrivateLinkServiceConnections  `json:"privateLinkServiceConnections"`
    ...

Otherwise, you have to explicitly specify the structure of each struct every time you initialize an instance, like:否则,您必须在每次初始化实例时明确指定每个结构的结构,例如:

x:=struct {
        Name       string `json:"name"`
        Properties struct {
            PrivateLinkServiceID              string `json:"privateLinkServiceId"`
            GroupIds                          string `json:"groupIds"`
            PrivateLinkServiceConnectionState struct {
                Status          string `json:"status"`
                Description     string `json:"description"`
                ActionsRequired string `json:"actionsRequired"`
            } `json:"privateLinkServiceConnectionState"`
        } `json:"properties"`
    }{ 
     Name:"name",
     Properties:struct {
            PrivateLinkServiceID              string `json:"privateLinkServiceId"`
            GroupIds                          string `json:"groupIds"`
            PrivateLinkServiceConnectionState struct {
                Status          string `json:"status"`
                Description     string `json:"description"`
                ActionsRequired string `json:"actionsRequired"`
            } `json:"privateLinkServiceConnectionState"`
        } { 
       PrivateLinkServiceID: id,
     },
 }

storageAccount.PrivateLinkServiceconnections=append(storageAccount.PrivateLinkServiceConnections, x)
...

PrivateLinkServiceConnections is defined as an array. PrivateLinkServiceConnections被定义为一个数组。 You cannot access it as you do with objects.您不能像访问对象那样访问它。 To add items to it, you need to use append function.要向其中添加项目,您需要使用append function。

Also, you have defined it as an inline anonymous struct, hence your code has become messy.此外,您已将其定义为内联匿名结构,因此您的代码变得混乱。 Define a specific type for PrivateLinkServiceConnections and then each time on append, simply assign it without the need to redeclare it.为 PrivateLinkServiceConnections 定义一个特定的类型,然后每次在 append 上,只需分配它,无需重新声明它。 It is a bad practice.这是一种不好的做法。

At first I did a workaround to add "[]" that I needed and it worked but it was not great.起初我做了一个解决方法来添加我需要的“[]”并且它有效但它不是很好。

But now I finally undertood how to it但现在我终于明白了

#models file #模型文件

type AccessPolicieS struct {
TenantID string `json:"tenantId"`
ObjectID string `json:"objectId"`
Permissions struct {
    Keys         []string `json:"keys"`
    Secrets      []string `json:"secrets"`
    Certificates []string `json:"certificates"`
    } `json:"permissions"`
}

    type AzVaultPriv struct {
    Properties struct {
        AccessPolicies []AccessPolicieS
    } `json:"properties"`
}


acessP := models.AccessPolicieS{}
    acessP.TenantID  = "*******"
    acessP.Permissions.Keys = append(acessP.Permissions.Keys, "UnwrapKey")
    acessP.Permissions.Keys = append(acessP.Permissions.Keys, "WrapKey")
    acessP.Permissions.Keys = append(acessP.Permissions.Keys, "Get")
    acessP.Permissions.Secrets = append(acessP.Permissions.Secrets, "get")
    acessP.Permissions.Certificates = 
    append(acessP.Permissions.Certificates, "get")

    newModel := models.AzVaultPriv {}
    newModel.Properties.AccessPolicies = append(newModel.Properties.AccessPolicies, acessP)
    marshaledObject, _ := json.Marshal(newModel)

Follow below a work around that's not ideal, but kept me going foward until I fixed this.按照下面的一个不理想的解决方法,但让我继续前进,直到我解决了这个问题。

func FormatJsonStructVaultPriv(json []byte) []byte {
    json = bytes.Replace(json, []byte("Policies\":{"), []byte("Policies\":[{"), 1)
    json = bytes.Replace(json, []byte("get\"]}}}}"), []byte("get\"]}}]}}"), 1)
    return json
}

Thanks for the help!谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM