aboutsummaryrefslogtreecommitdiff
path: root/contact.go
blob: 71b4ecd7f66319f0e86ee105abd5bff4abc01d40 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
package acme

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

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

type Contact interface {
	encoding.TextMarshaler
}

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
}

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
}

func NewContacts(email, phone string) (Contacts, error) {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return nil, err
	}
	c := Contacts{Mail(m.Address)}
	if phone != "" {
		c = append(c, Phone(phone))
	}
	return c, nil
}