我目前正在嘗試使用 golang 創建以下嵌套 json,包括證書的 json 和 DER 編碼字節數組 () 列表:{"webhooks": [{ "clientConfig":{ "caBundle":"<derData []bytes>" }, "name":"sth_name" }]}因為<certDerBytes[]>,我需要使用一個結構體,但我不知道如何初始化它。到目前為止我已經創建了該結構:type jsonstruct struct { Webhooks []struct { ClientConfig struct { CaBundle string `json:"caBundle"` } `json:"clientConfig"` Name string `json:"name"` } `json:"webhooks"`}但無法實例化我必須編組為 json 的結構。我嘗試過使用字符串文字,以及許多初始化它的方法,就像使用普通的非嵌套結構一樣。我還劃分了結構 ietype jsonstruct.. type webhooks ...等,但是出錯了。我還從內到外初始化了該結構,但也不起作用。
1 回答

RISEBY
TA貢獻1856條經驗 獲得超5個贊
您最好可能使用base64字節數組本身,并將其作為結構字段的有效負載。
一件小事,我個人不喜歡嵌套的命名結構。將它們分開可以讓您的代碼更加靈活。
例如:
type jsonstruct struct {
Webhooks []Webhook `json:"webhooks"`
}
type Webhook struct {
ClientConfig ClientConfig `json:"clientConfig"`
Name string `json:"name"`
}
type ClientConfig struct {
CaBundle string `json:"caBundle"`
}
func (cc ClientConfig) ToBytes() []byte {
return []byte(base64.StdEncoding.DecodeString(cc.CaBundle))
}
func (cc ClientConfig) FromBytes(cert []byte) {
cc.CaBundle = base64.StdEncoding.EncodeToString(cert)
}
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消