urn8141.go 529 B

123456789101112131415161718192021222324252627282930
  1. package urn
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. const errInvalidURN8141 = "invalid URN per RFC 8141: %s"
  7. type URN8141 struct {
  8. *URN
  9. }
  10. func (u URN8141) MarshalJSON() ([]byte, error) {
  11. return json.Marshal(u.String())
  12. }
  13. func (u *URN8141) UnmarshalJSON(bytes []byte) error {
  14. var str string
  15. if err := json.Unmarshal(bytes, &str); err != nil {
  16. return err
  17. }
  18. if value, ok := Parse([]byte(str), WithParsingMode(RFC8141Only)); !ok {
  19. return fmt.Errorf(errInvalidURN8141, str)
  20. } else {
  21. *u = URN8141{value}
  22. }
  23. return nil
  24. }