Skip to content

Commit 0d23439

Browse files
authored
Adding a UUID format (#546)
* Adding a UUID format * Removing indirect (hopefully build passes now) Co-authored-by: Chrusty <>
1 parent fd0f800 commit 0d23439

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

uuid.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package types
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
7+
"github.com/google/uuid"
8+
)
9+
10+
type UUID string
11+
12+
func (u UUID) MarshalJSON() ([]byte, error) {
13+
if _, err := uuid.Parse(string(u)); err != nil {
14+
return nil, errors.New("uuid: failed to pass validation")
15+
}
16+
return json.Marshal(string(u))
17+
}
18+
19+
func (u *UUID) UnmarshalJSON(data []byte) error {
20+
var s string
21+
if err := json.Unmarshal(data, &s); err != nil {
22+
return err
23+
}
24+
if _, err := uuid.Parse(s); err != nil {
25+
return errors.New("uuid: failed to pass validation")
26+
}
27+
*u = UUID(s)
28+
return nil
29+
}

uuid_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package types
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestUUID_MarshalJSON_Fail(t *testing.T) {
11+
testUUID := "this-is-not-a-uuid"
12+
b := struct {
13+
UUIDField UUID `json:"uuid"`
14+
}{
15+
UUIDField: UUID(testUUID),
16+
}
17+
_, err := json.Marshal(b)
18+
assert.Error(t, err)
19+
}
20+
21+
func TestUUID_MarshalJSON_Pass(t *testing.T) {
22+
testUUID := "9cb14230-b640-11ec-b909-0242ac120002"
23+
b := struct {
24+
UUIDField UUID `json:"uuid"`
25+
}{
26+
UUIDField: UUID(testUUID),
27+
}
28+
jsonBytes, err := json.Marshal(b)
29+
assert.NoError(t, err)
30+
assert.JSONEq(t, `{"uuid":"9cb14230-b640-11ec-b909-0242ac120002"}`, string(jsonBytes))
31+
}
32+
33+
func TestUUID_UnmarshalJSON_Fail(t *testing.T) {
34+
jsonStr := `{"uuid":"this-is-not-a-uuid"}`
35+
b := struct {
36+
UUIDField UUID `json:"uuid"`
37+
}{}
38+
err := json.Unmarshal([]byte(jsonStr), &b)
39+
assert.Error(t, err)
40+
}
41+
42+
func TestUUID_UnmarshalJSON_Pass(t *testing.T) {
43+
testUUID := UUID("9cb14230-b640-11ec-b909-0242ac120002")
44+
jsonStr := `{"uuid":"9cb14230-b640-11ec-b909-0242ac120002"}`
45+
b := struct {
46+
UUIDField UUID `json:"uuid"`
47+
}{}
48+
err := json.Unmarshal([]byte(jsonStr), &b)
49+
assert.NoError(t, err)
50+
assert.Equal(t, testUUID, b.UUIDField)
51+
}

0 commit comments

Comments
 (0)