forked from gptankit/serviceq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistener.go
64 lines (51 loc) · 1.31 KB
/
listener.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
package main
import (
"crypto/rand"
"crypto/tls"
"model"
"net"
"time"
)
func getListener(sqp model.ServiceQProperties) (net.Listener, error) {
transport := "tcp"
addr := ":" + sqp.ListenerPort
certificate := sqp.SSLCertificateFile
key := sqp.SSLPrivateKeyFile
if !sqp.SSLEnabled {
return newListener(transport, addr)
} else {
return newListener(transport, addr, applyTLS(certificate, key))
}
}
func newListener(transport string, addr string, options ...func(*net.Listener) error) (net.Listener, error) {
listener, err := net.Listen(transport, addr)
if err != nil {
return listener, err
}
for _, option := range options {
err = option(&listener)
if err != nil {
return listener, err // further options won't be executed
}
}
return listener, nil
}
func applyTLS(certificate string, key string) func(*net.Listener) error {
return func(l *net.Listener) error {
cert, err := tls.LoadX509KeyPair(certificate, key)
if err != nil {
return err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "serviceq",
NextProtos: []string{"http/1.1", "http/1.0"},
Time: time.Now,
Rand: rand.Reader,
}
tlsConfig.BuildNameToCertificate()
tlsConfig.PreferServerCipherSuites = true
*l = tls.NewListener(*l, tlsConfig)
return nil
}
}