Skip to content

Instantly share code, notes, and snippets.

@j0sh
Created December 21, 2023 19:47
Show Gist options
  • Save j0sh/93521ec3476656d6f620f0e421801228 to your computer and use it in GitHub Desktop.
Save j0sh/93521ec3476656d6f620f0e421801228 to your computer and use it in GitHub Desktop.
package main
import "encoding/base64"
type Base64URLBlob []byte
var b64 = base64.URLEncoding
func (b Base64URLBlob) MarshalJSON() ([]byte, error) {
dst := make([]byte, b64.EncodedLen(len(b))+2)
dst[0], dst[len(dst)-1] = '"', '"'
b64.Encode(dst[1:], []byte(b))
return dst, nil
}
func (b *Base64URLBlob) UnmarshalJSON(p []byte) error {
if len(p) < 2 {
return nil
}
// Handle double quotes
if p[0] == '"' && p[len(p)-1] == '"' {
p = p[1 : len(p)-1]
}
dst := make([]byte, b64.DecodedLen(len(p)))
n, err := b64.Decode(dst, p)
if err != nil {
return err
}
*b = Base64URLBlob(dst[:n])
return nil
}
package main
import (
"encoding/json"
"testing"
"testing/quick"
)
// Base64URLBlob and its methods (MarshalJSON and UnmarshalJSON) are assumed to be defined here.
// checkConsistency ensures that marshaling and then unmarshaling a Base64URLBlob results in the original blob.
func checkConsistency(b Base64URLBlob) bool {
marshaled, err := json.Marshal(b)
if err != nil {
return false
}
var unmarshaled Base64URLBlob
err = json.Unmarshal(marshaled, &unmarshaled)
if err != nil {
return false
}
// Check if original and unmarshaled are the same
return string(b) == string(unmarshaled)
}
// TestBase64URLBlobConsistency uses quickcheck to test the consistency of Base64URLBlob's marshal and unmarshal methods.
func TestBase64URLBlobConsistency(t *testing.T) {
if err := quick.Check(checkConsistency, nil); err != nil {
t.Error(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment