亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 的 YAML 中將字節數組呈現為字符串?

如何在 Go 的 YAML 中將字節數組呈現為字符串?

Go
皈依舞 2023-02-21 12:55:44
我有一個以字節數組作為字段的結構。這是代碼:package mainimport (    "fmt"    "gopkg.in/yaml.v3")type A struct {    PublicKey []byte `json:"PublicKey" yaml:"PublicKey"`}// Implements the Marshaler interface of the yaml pkg.func (a A) MarshalYAML() (interface{}, error) {    type alias A    node := yaml.Node{}    _ = node.Encode(alias(a))    return node, nil}func PublicKey() {    token := []byte{87, 88, 89, 90}    a := A{PublicKey: token}    fmt.Printf("A: %+v\nA.PublicKey:%s\n\n", a, a.PublicKey)    out, _ := yaml.Marshal(a)    fmt.Println(string(out))}func main() {    PublicKey()}這是輸出:A: {PublicKey:[87 88 89 90]}A.PublicKey:WXYZPublicKey:    - 87    - 88    - 89    - 90是否可以讓 marshal-er 將其輸出為字符串而不是字節數組?例如:PublicKey: WXYZ
查看完整描述

1 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

與其自定義編解碼器,不如A為公鑰創建自定義類型并使用 Base64 對其值進行編碼/解碼


type PubKey []byte


func (pk PubKey) MarshalYAML() (interface{}, error) {

    return base64.StdEncoding.EncodeToString(pk), nil

}


func (pk *PubKey) UnmarshalYAML(node *yaml.Node) error {

    value := node.Value

    ba, err := base64.StdEncoding.DecodeString(value)

    if err != nil {

        return err

    }

    *pk = ba

    return nil

}


type A struct {

    PublicKey PubKey `json:"PublicKey" yaml:"PublicKey"`

}


// No custom YAML codec

編碼/解碼是這樣的:


func PublicKey() {

    token := []byte{87, 88, 89, 90}


    a := A{PublicKey: token}


    fmt.Printf("A: %+v\nA.PublicKey:%s\n\n", a, a.PublicKey)

    out, _ := yaml.Marshal(a)

    fmt.Println("Encoded: ", string(out))


    var b A

    err := yaml.Unmarshal(out, &b)

    if err != nil {

        println(err)

    }

    fmt.Printf("after decoding: %+v\n", b)

}

完整示例https://go.dev/play/p/2_gMi9sazIp


結果是:


A: {PublicKey:[87 88 89 90]}

A.PublicKey:WXYZ


Encoded:  PublicKey: V1hZWg==


after decoding: {PublicKey:[87 88 89 90]}

順便說一句,base64 是編解碼器如何json編組字節切片 示例與您的數據:https://go.dev/play/p/dGr0i0DnnNX


A: {PublicKey:[87 88 89 90]}

A.PublicKey:WXYZ


Encoded JSON:  {"PublicKey":"V1hZWg=="}

after decoding JSON: {PublicKey:[87 88 89 90]}


查看完整回答
反對 回復 2023-02-21
  • 1 回答
  • 0 關注
  • 219 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號