This repository has been archived by the owner on Oct 2, 2022. It is now read-only.
generated from ContainerSSH/library-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_impl.go
89 lines (83 loc) · 1.62 KB
/
server_impl.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
85
86
87
88
89
package http
import (
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
goHttp "net/http"
"sync"
"github.com/containerssh/service"
)
type server struct {
name string
lock *sync.Mutex
handler goHttp.Handler
config ServerConfiguration
tlsConfig *tls.Config
srv *goHttp.Server
goLogger io.Writer
onReady func(string)
}
func (s *server) String() string {
return s.name
}
func (s *server) RunWithLifecycle(lifecycle service.Lifecycle) error {
s.lock.Lock()
if s.srv != nil {
return fmt.Errorf("server is already running")
}
s.srv = &goHttp.Server{
Addr: s.config.Listen,
Handler: s.handler,
TLSConfig: s.tlsConfig,
ErrorLog: log.New(s.goLogger, "", 0),
}
defer func() {
s.lock.Lock()
s.srv = nil
s.lock.Unlock()
}()
var err error
ln, err := net.Listen("tcp", s.srv.Addr)
if err != nil {
s.lock.Unlock()
return err
}
defer func() { _ = ln.Close() }()
var url string
if s.srv.TLSConfig != nil {
url = fmt.Sprintf("https://%s", s.config.Listen)
} else {
url = fmt.Sprintf("http://%s", s.config.Listen)
}
s.onReady(url)
lifecycle.Running()
s.lock.Unlock()
serverFinished := make(chan struct{}, 1)
go func() {
select {
case <-lifecycle.Context().Done():
s.lock.Lock()
if s.srv == nil {
s.lock.Unlock()
return
}
srv := s.srv
s.lock.Unlock()
_ = srv.Shutdown(lifecycle.ShutdownContext())
case <-serverFinished:
}
}()
if s.srv.TLSConfig != nil {
err = s.srv.ServeTLS(ln, "", "")
} else {
err = s.srv.Serve(ln)
}
serverFinished <- struct{}{}
if err != nil && !errors.Is(err, goHttp.ErrServerClosed) {
return err
}
return nil
}