-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.go
More file actions
85 lines (76 loc) · 1.74 KB
/
httpserver.go
File metadata and controls
85 lines (76 loc) · 1.74 KB
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
package httpserver
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/blbgo/general"
)
type httpServer struct {
*http.Server
Config
general.Shutdowner
closing bool
}
// New creates and starts an http server returning a general.DelayCloser that will allow clean
// shutdown
func New(config Config, handler http.Handler, shutdowner general.Shutdowner) general.DelayCloser {
r := &httpServer{
Server: &http.Server{
Addr: config.Addr(), //":1333",
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: handler,
},
Config: config,
Shutdowner: shutdowner,
}
go r.httpServerThread()
return r
}
func (r *httpServer) httpServerThread() {
var err error
if r.HTTPS() {
err = r.ListenAndServeTLS(r.CertFile(), r.KeyFile())
} else {
err = r.ListenAndServe()
}
if !r.closing {
r.closing = true
fmt.Println("httpServer.ListenAndServe returned before Close called")
fmt.Println("must be startup error, shutting down")
r.Shutdowner.Shutdown(err)
return
}
if err == http.ErrServerClosed {
fmt.Println("ListenAndServe returned http.ErrServerClosed")
return
}
if err != nil {
fmt.Println(err)
os.Exit(2)
}
}
func (r *httpServer) Close(doneChan chan<- error) {
go r.closeServer(doneChan)
}
func (r *httpServer) closeServer(doneChan chan<- error) {
// already closing must have been startup error
if r.closing {
doneChan <- nil
return
}
r.closing = true
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
err := r.Server.Shutdown(ctx)
if err != nil {
fmt.Println("Error on http server shutdown: ", err)
doneChan <- err
return
}
fmt.Println("Clean http server shutdown.")
doneChan <- nil
}