atom/category.go

76 lines
1.7 KiB
Go

package atom
import (
"encoding/xml"
"errors"
"fmt"
"html"
)
type Category struct {
XMLName xml.Name `xml:"category"`
*CommonAttributes
Term string `xml:"term,attr"`
Scheme string `xml:"scheme,attr,omitempty"` // IRI
Label string `xml:"label,attr,omitempty"`
}
// NewCategory creates a new Category. It returns a *Category and an error.
func NewCategory(term string) (*Category, error) {
if term == "" {
return nil, errors.New("error creating new category: term string empty")
}
return &Category{Term: term}, nil
}
// SetTerm sets the Term attribute of the Category. It returns an error.
func (c *Category) SetTerm(t string) error {
if t == "" {
return errors.New("error setting term of category: t string empty")
}
c.Term = t
return nil
}
// SetScheme sets the Scheme attribute of the Category. It returns an error.
func (c *Category) SetScheme(s string) error {
if !isValidIRI(s) {
return fmt.Errorf("scheme %v not correctly formatted", s)
}
c.Scheme = s
return nil
}
// SetLabel sets the Label attribute of the Category. It returns an error.
func (c *Category) SetLabel(label string) error {
if label == "" {
return errors.New("error setting label of category: label string empty")
}
c.Label = html.UnescapeString(label)
return nil
}
// Check checks the Category for incompatibilities with RFC4287. It returns an
// error.
func (c *Category) Check() error {
if c.Term == "" {
return fmt.Errorf("term attribute of category %v empty", c)
}
if c.Scheme != "" {
if !isValidIRI(c.Scheme) {
return fmt.Errorf("scheme attribute of category %v not correctly formatted", c)
}
}
if !isCorrectlyEscaped(c.Label) {
return fmt.Errorf("label attribute of category %v not correctly escaped", c)
}
return nil
}