为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 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 关注
  • 232 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号