1 回答

TA貢獻1853條經驗 獲得超6個贊
在 DTO 結構外部定義您的 ServiceAccount 結構,以便您可以重用它。
由于您正在定義結構內部的結構,因此在創建對象時還需要再次定義它,如下所示:ServiceAccountsServiceAccountRequestDTO
Data := dto.ServiceAccountRequestDTO{
ServiceAccounts : []struct{
WorkspaceID int64 `json:"workspace_id"`
ServiceAccountName string `json:"serviceAccountName"`
ServiceAccountKey ServiceAccountKey `json:"serviceAccountKey"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CreatedBy string `json:"created_by"`
UpdatedBy string `json:"updated_by"`
} `json:"serviceAccounts"`{ //start of slice (it's technically not an array) of objects
{ // first object
WorkspaceID: 1,
ServiceAccountName: "sa-10",
ServiceAccountKey: dto.ServiceAccountKey{
Type: "service_account",
ProjectID: "abc",
PrivateKeyID: "123",
PrivateKey: "234",
ClientEmail: "read-clusters",
ClientID: "cdf",
AuthURI: "https://accounts.google.com/o/oaut",
TokenURI: "https://oauth2.googleapis.com/token",
AuthProviderX509CertURL: "https://www.googleapis.com",
ClientX509CertURL: "xwy",
},
CreatedAt: "2021-03-08 17:05:21.0",
UpdatedAt: "2021-03-08 17:05:21.0",
CreatedBy: "user-01",
UpdatedBy: "user-01",
},
// .. more ServiceAccount objects ...
},
}
現在,這當然是令人難以置信的痛苦的編寫和閱讀,并復制了很多代碼。因此,您應該在外部定義結構。
type ServiceAccount struct{
WorkspaceID int64 `json:"workspace_id"`
ServiceAccountName string `json:"serviceAccountName"`
ServiceAccountKey ServiceAccountKey `json:"serviceAccountKey"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CreatedBy string `json:"created_by"`
UpdatedBy string `json:"updated_by"`
} `json:"serviceAccounts"`
}
type ServiceAccountRequestDTO struct {
ServiceAccounts []ServiceAccount
}
然后你可以像這樣創建你的DTO
Data := dto.ServiceAccountRequestDTO{
ServiceAccounts : []ServiceAccount{ //start of slice of objects
ServiceAccount { // first object
WorkspaceID: 1,
ServiceAccountName: "sa-10",
ServiceAccountKey: dto.ServiceAccountKey{
Type: "service_account",
ProjectID: "abc",
PrivateKeyID: "123",
PrivateKey: "234",
ClientEmail: "read-clusters",
ClientID: "cdf",
AuthURI: "https://accounts.google.com/o/oaut",
TokenURI: "https://oauth2.googleapis.com/token",
AuthProviderX509CertURL: "https://www.googleapis.com",
ClientX509CertURL: "xwy",
},
CreatedAt: "2021-03-08 17:05:21.0",
UpdatedAt: "2021-03-08 17:05:21.0",
CreatedBy: "user-01",
UpdatedBy: "user-01",
},
// .. more ServiceAccount objects ...
},
}
- 1 回答
- 0 關注
- 93 瀏覽
添加回答
舉報