-
Notifications
You must be signed in to change notification settings - Fork 7
/
example_tls_test.go
80 lines (65 loc) · 1.66 KB
/
example_tls_test.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
70
71
72
73
74
75
76
77
78
79
80
package netconf_test
import (
"context"
"crypto/tls"
"crypto/x509"
_ "embed"
"fmt"
"log"
"os"
"time"
"github.com/nemith/netconf"
nctls "github.com/nemith/netconf/transport/tls"
)
const tlsAddr = "myrouter.example.com:6513"
func Example_tls() {
caCert, err := os.ReadFile("ca.crt")
if err != nil {
log.Fatalf("failed to load ca cert: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
clientCert, err := os.ReadFile("client.crt")
if err != nil {
log.Fatalf("failed to load client cert: %v", err)
}
clientKey, err := os.ReadFile("client.key")
if err != nil {
log.Fatalf("failed to load client key: %v", err)
}
cert, err := tls.X509KeyPair(clientCert, clientKey)
if err != nil {
panic(err)
}
// tls transport configuration
config := tls.Config{
InsecureSkipVerify: true,
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
}
// Add a connection establish timeout of 5 seconds. You can also accomplish
// the same behavior with Timeout field of the ssh.ClientConfig.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
transport, err := nctls.Dial(ctx, "tcp", tlsAddr, &config)
if err != nil {
panic(err)
}
defer transport.Close()
session, err := netconf.Open(transport)
if err != nil {
panic(err)
}
defer session.Close(context.Background())
// timeout for the call itself.
ctx, cancel = context.WithTimeout(ctx, 5*time.Second)
defer cancel()
cfg, err := session.GetConfig(ctx, "running")
if err != nil {
panic(err)
}
fmt.Printf("Config: %s\n", cfg)
if err := session.Close(context.Background()); err != nil {
log.Print(err)
}
}