aboutsummaryrefslogtreecommitdiff
path: root/contact.go
blob: 8b0b05499fc7f3baf61fda664e7b0a225888167b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package acme

import (
	"encoding"
	"encoding/json"
	"errors"
	"strings"
)

var errInvalidContact = errors.New("Ivalid contact")

type Contact interface {
	encoding.TextMarshaler
}

type Mail string

func (m Mail) MarshalText() ([]byte, error) {
	return []byte("mailto:" + m), nil
}

type Phone string

func (ph Phone) MarshalText() ([]byte, error) {
	return []byte("tel:" + ph), nil
}

type Contacts []Contact

func (c *Contacts) UnmarshalJSON(b []byte) error {
	var tmp []string
	err := json.Unmarshal(b, &tmp)
	if err != nil {
		return err
	}
	*c = nil // invalidate old value
	for _, s := range tmp {
		switch {
		case strings.HasPrefix(s, "mailto:"):
			*c = append(*c, Mail(s[7:]))
		case strings.HasPrefix(s, "tel:"):
			*c = append(*c, Phone(s[4:]))
		default:
			return errInvalidContact
		}
	}
	return nil
}