-
Notifications
You must be signed in to change notification settings - Fork 7
/
get.go
68 lines (64 loc) · 1.52 KB
/
get.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
package snmp
import (
"fmt"
"github.com/masiulaniec/snmp/mib"
)
// Get retrieves an object by its name. Nameval is a pair of: object
// name (string), and the corresponding target value (pointer to int,
// string, etc.). To retrieve multiple objects in a single transaction,
// provide multiple name, value pairs.
func Get(host, community string, nameval ...interface{}) error {
switch n := len(nameval); {
case n == 0:
return nil
case n%2 == 1:
panic("snmp.Get: odd-sized nameval")
}
bindings, err := fromPairs(nameval)
if err != nil {
return err
}
tr, err := newTransport(host, community)
if err != nil {
return err
}
req := &Request{
Type: "Get",
Bindings: bindings,
ID: <-nextID,
}
resp, err := tr.RoundTrip(req)
if err != nil {
return err
}
if err := check(resp, req); err != nil {
return err
}
for i, b := range resp.Bindings {
if have, want := b.Name, req.Bindings[i].Name; !have.Equal(want) {
return fmt.Errorf("snmp: %s: get %s: invalid response: name mismatch",
host, want)
}
v := nameval[2*i+1]
if err := b.unmarshal(v); err != nil {
return err
}
}
return nil
}
// fromPairs creates bindings from the (name, value) pairs.
func fromPairs(nameval []interface{}) ([]Binding, error) {
var bindings []Binding
for i := 0; i < len(nameval); i += 2 {
s, ok := nameval[i].(string)
if !ok {
panic("pair name not a string")
}
oid, err := mib.Lookup(s)
if err != nil {
return nil, err
}
bindings = append(bindings, Binding{Name: oid})
}
return bindings, nil
}