forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
69 lines (56 loc) · 1.57 KB
/
connection.go
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
package gobot
import (
"log"
"reflect"
multierror "github.com/hashicorp/go-multierror"
)
// JSONConnection is a JSON representation of a Connection.
type JSONConnection struct {
Name string `json:"name"`
Adaptor string `json:"adaptor"`
}
// NewJSONConnection returns a JSONConnection given a Connection.
func NewJSONConnection(connection Connection) *JSONConnection {
return &JSONConnection{
Name: connection.Name(),
Adaptor: reflect.TypeOf(connection).String(),
}
}
// A Connection is an instance of an Adaptor
type Connection Adaptor
// Connections represents a collection of Connection
type Connections []Connection
// Len returns connections length
func (c *Connections) Len() int {
return len(*c)
}
// Each enumerates through the Connections and calls specified callback function.
func (c *Connections) Each(f func(Connection)) {
for _, connection := range *c {
f(connection)
}
}
// Start calls Connect on each Connection in c
func (c *Connections) Start() (err error) {
log.Println("Starting connections...")
for _, connection := range *c {
info := "Starting connection " + connection.Name()
if porter, ok := connection.(Porter); ok {
info = info + " on port " + porter.Port()
}
log.Println(info + "...")
if cerr := connection.Connect(); cerr != nil {
err = multierror.Append(err, cerr)
}
}
return err
}
// Finalize calls Finalize on each Connection in c
func (c *Connections) Finalize() (err error) {
for _, connection := range *c {
if cerr := connection.Finalize(); cerr != nil {
err = multierror.Append(err, cerr)
}
}
return err
}