1
0
Fork 0

🏷️ Created Type domain

This commit is contained in:
Maxim Lebedev 2023-11-26 00:11:30 +06:00
parent 8703bf8cbe
commit 2428c890e7
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
2 changed files with 113 additions and 0 deletions

62
type.go Normal file
View File

@ -0,0 +1,62 @@
package jf2
import (
"fmt"
"strconv"
"strings"
)
// Type defines the object classification.
//
// In microformats, this is presumed to be an h-* class from the microformats2
// vocabulary.
type Type struct{ value string }
var (
TypeUnd Type = Type{} // "und"
TypeAdr Type = Type{"adr"} // "adr"
TypeCard Type = Type{"card"} // "card"
TypeEntry Type = Type{"entry"} // "entry"
TypeEvent Type = Type{"event"} // "event"
TypeFeed Type = Type{"feed"} // "feed"
TypeGeo Type = Type{"geo"} // "geo"
TypeItem Type = Type{"item"} // "item"
TypeListing Type = Type{"listing"} // "listing"
TypeProduct Type = Type{"product"} // "product"
TypeRecipe Type = Type{"recipe"} // "recipe"
TypeResume Type = Type{"resume"} // "resume"
TypeReview Type = Type{"review"} // "review"
TypeReviewAggregate Type = Type{"review-aggregate"} // "review-aggregate"
)
func (t *Type) UnmarshalJSON(v []byte) error {
unquoted, err := strconv.Unquote(string(v))
if err != nil {
return fmt.Errorf("JF2: Type: cannot unquote value: %w", err)
}
t.value = strings.ToLower(strings.TrimSpace(unquoted))
return nil
}
func (t Type) MarshalJSON() ([]byte, error) {
if t.value != "" {
return []byte(strconv.Quote(t.value)), nil
}
return nil, nil
}
func (t Type) String() string {
if t.value != "" {
return t.value
}
return "und"
}
func (t Type) GoString() string {
return "jf2.Type(" + t.String() + ")"
}

51
type_test.go Normal file
View File

@ -0,0 +1,51 @@
package jf2_test
import (
"encoding/json"
"testing"
"source.toby3d.me/toby3d/jf2"
)
func TestType_UnmarshalJSON(t *testing.T) {
t.Parallel()
v := new(struct {
Type jf2.Type `json:"type"`
Author struct {
Type jf2.Type `json:"type"`
} `json:"author"`
})
if err := json.Unmarshal([]byte(`{"type":"entry","author":{"type":"card"}}`), v); err != nil {
t.Fatal(err)
}
for actual, target := range map[jf2.Type]jf2.Type{
v.Type: jf2.TypeEntry,
v.Author.Type: jf2.TypeCard,
} {
if actual == target {
continue
}
t.Errorf("got '%s', want '%s'", actual, target)
}
}
func TestType_MarshalJSON(t *testing.T) {
t.Parallel()
body, err := json.Marshal(struct {
Type jf2.Type `json:"type"`
}{
Type: jf2.TypeCard,
})
if err != nil {
t.Fatal(err)
}
const expect string = `{"type":"card"}`
if actual := string(body); actual != expect {
t.Errorf("got '%s', want '%s'", actual, expect)
}
}