File size: 2,127 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package twiml

import (
	"encoding/xml"
	"errors"
	"fmt"
)

type (
	v struct{}

	// GatherVerb is any verb that can be nested inside a Gather.
	GatherVerb interface {
		Verb
		isGatherVerb() v // unexported method to prevent external implementations
	}

	// Verb is any verb that can be nested inside a Response.
	Verb interface {
		isVerb() v // unexported method to prevent external implementations
	}
)

func (*Pause) isGatherVerb() v { return v{} }
func (*Say) isGatherVerb() v   { return v{} }

func (*Pause) isVerb() v    { return v{} }
func (*Say) isVerb() v      { return v{} }
func (*Gather) isVerb() v   { return v{} }
func (*Hangup) isVerb() v   { return v{} }
func (*Redirect) isVerb() v { return v{} }
func (*Reject) isVerb() v   { return v{} }

type anyVerb struct {
	verb Verb
}

func decodeVerb(d *xml.Decoder, start xml.StartElement) (Verb, error) {
	switch start.Name.Local {
	case "Gather":
		g := new(Gather)
		return g, d.DecodeElement(&g, &start)
	case "Hangup":
		h := new(Hangup)
		return h, d.DecodeElement(&h, &start)
	case "Pause":
		p := new(Pause)
		return p, d.DecodeElement(&p, &start)
	case "Redirect":
		r := new(Redirect)
		return r, d.DecodeElement(&r, &start)
	case "Reject":
		re := new(Reject)
		return re, d.DecodeElement(&re, &start)
	case "Say":
		s := new(Say)
		return s, d.DecodeElement(&s, &start)
	}

	return nil, errors.New("unsupported verb: " + start.Name.Local)
}

func encodeVerb(e *xml.Encoder, v Verb) error {
	var name string
	switch v.(type) {
	case *Gather:
		name = "Gather"
	case *Hangup:
		name = "Hangup"
	case *Pause:
		name = "Pause"
	case *Redirect:
		name = "Redirect"
	case *Reject:
		name = "Reject"
	case *Say:
		name = "Say"
	default:
		return fmt.Errorf("unsupported verb: %T", v)
	}

	if err := e.EncodeElement(v, xml.StartElement{Name: xml.Name{Local: name}}); err != nil {
		return err
	}

	return nil
}

func (v *anyVerb) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) {
	v.verb, err = decodeVerb(d, start)
	return err
}

func (v anyVerb) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) {
	return encodeVerb(e, v.verb)
}