Commit 9e6f63a
pkg/serde/io.go
@@ -17,6 +17,8 @@ func To[T any](w io.Writer, item T, mediaType MediaType) error {
return ToJSONAPI[T](w, item)
case Text:
return ToPlain[T](w, item)
+ case YAML:
+ return ToYAML[T](w, item)
default:
return ToJSON[T](w, item)
}
pkg/serde/io_test.go
@@ -11,8 +11,8 @@ import (
func TestFrom(t *testing.T) {
type Example struct {
- Key string `json:"key" jsonapi:"primary,examples"`
- Value string `json:"value" jsonapi:"attr,value"`
+ Key string `json:"key" jsonapi:"primary,examples" yaml:"key"`
+ Value string `json:"value" jsonapi:"attr,value" yaml:"value"`
}
t.Run("parses a single item from JSON data", func(t *testing.T) {
@@ -207,6 +207,18 @@ func TestTo(t *testing.T) {
Value: "my-value",
}}, JSONAPI))
expected := `{"data":[{"type":"examples","id":"my-key","attributes":{"value":"my-value"}}]}
+`
+ assert.Equal(t, expected, w.String())
+ })
+
+ t.Run("serializes an item to YAML", func(t *testing.T) {
+ w := bytes.NewBuffer(nil)
+ require.NoError(t, To[Example](w, Example{
+ Key: "my-key",
+ Value: "my-value",
+ }, YAML))
+ expected := `key: my-key
+value: my-value
`
assert.Equal(t, expected, w.String())
})
pkg/serde/media.go
@@ -15,6 +15,7 @@ const (
JSONAPI MediaType = jsonapi.MediaType
JSON MediaType = "application/json"
Text MediaType = "text/plain"
+ YAML MediaType = "application/yaml"
Default MediaType = JSON
)
pkg/serde/yaml.go
@@ -0,0 +1,11 @@
+package serde
+
+import (
+ "io"
+
+ "gopkg.in/yaml.v2"
+)
+
+func ToYAML[T any](w io.Writer, item T) error {
+ return yaml.NewEncoder(w).Encode(item)
+}
go.mod
@@ -5,6 +5,7 @@ go 1.18
require (
github.com/google/jsonapi v1.0.0
github.com/stretchr/testify v1.8.0
+ gopkg.in/yaml.v2 v2.4.0
)
require (
go.sum
@@ -12,6 +12,8 @@ github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PK
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=