From 49b82ace71967a53bf1edc985e2a1d94227f2ac5 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Fri, 25 Aug 2023 16:12:27 +0000 Subject: [PATCH] wireguard: implement MarshalJSON for PrivateKey and PublicKey Signed-off-by: Alejandro Mery --- pkg/wireguard/keys.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/pkg/wireguard/keys.go b/pkg/wireguard/keys.go index 5e01599..6e82a90 100644 --- a/pkg/wireguard/keys.go +++ b/pkg/wireguard/keys.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "encoding/base64" "errors" + "fmt" "golang.org/x/crypto/curve25519" ) @@ -50,6 +51,25 @@ func (pub PublicKey) String() string { } } +// MarshalJSON encodes the key for JSON, omiting empty. +func (key PrivateKey) MarshalJSON() ([]byte, error) { + return encodeKeyJSON(key.String()) +} + +// MarshalJSON encodes the key for JSON, omiting empty. +func (pub PublicKey) MarshalJSON() ([]byte, error) { + return encodeKeyJSON(pub.String()) +} + +func encodeKeyJSON(s string) ([]byte, error) { + var out []byte + if s != "" { + out = []byte(fmt.Sprintf("%q", s)) + } + + return out, nil +} + // IsZero tells if the key hasn't been set func (key PrivateKey) IsZero() bool { var zero PrivateKey