-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
84 lines (67 loc) · 1.29 KB
/
tls.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
81
82
83
84
package httpserve
import (
"crypto/tls"
"fmt"
"os"
"path/filepath"
)
const (
invalidTLSFmt = "invalid tls certification pair, neither key nor cert can be empty (%s): %#v"
)
func newTLSCerts(dir string) (tc tlsCerts, err error) {
tc = make(tlsCerts)
err = filepath.Walk(dir, tc.walk)
return
}
type tlsCerts map[string]*tlsCert
func (t tlsCerts) get(name string) (tc *tlsCert) {
var ok bool
if tc, ok = t[name]; !ok {
tc = &tlsCert{}
t[name] = tc
}
return
}
func (t tlsCerts) walk(path string, info os.FileInfo, ierr error) (err error) {
if info.IsDir() {
return
}
end := len(path) - 4
name := path[:end]
ext := path[end:]
switch ext {
case ".crt":
t.get(name).cert = path
case ".key":
t.get(name).key = path
}
return
}
func (t tlsCerts) Certificates() (certs []tls.Certificate, err error) {
certs = make([]tls.Certificate, 0, len(t))
for name, tc := range t {
if !tc.isValid() {
err = fmt.Errorf(invalidTLSFmt, name, tc)
return
}
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(tc.cert, tc.key); err != nil {
return
}
certs = append(certs, cert)
}
return
}
type tlsCert struct {
key string
cert string
}
func (t *tlsCert) isValid() (ok bool) {
if len(t.key) == 0 {
return
}
if len(t.cert) == 0 {
return
}
return true
}