Showing
1 changed file
with
55 additions
and
5 deletions
... | ... | @@ -25,14 +25,21 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. |
25 | 25 | package test |
26 | 26 | |
27 | 27 | import ( |
28 | + "context" | |
28 | 29 | "encoding/json" |
30 | + "io" | |
29 | 31 | "net/http" |
32 | + "os" | |
33 | + "os/signal" | |
30 | 34 | "strings" |
31 | - //"os" | |
32 | - "io" | |
35 | + "syscall" | |
36 | + | |
37 | + "gitlab.weird-web-workers.org/golang/logger" | |
33 | 38 | ) |
34 | 39 | |
35 | -type ApiHandler struct {} | |
40 | +type ApiHandler struct { | |
41 | + log *logger.Logger | |
42 | +} | |
36 | 43 | |
37 | 44 | type version struct { |
38 | 45 | Version string `json:"Version"` |
... | ... | @@ -40,6 +47,12 @@ type version struct { |
40 | 47 | BuildTime string `json:"BuildTimestamp"` |
41 | 48 | } |
42 | 49 | |
50 | +type Server struct { | |
51 | + server *http.Server | |
52 | + log *logger.Logger | |
53 | + Stop chan bool | |
54 | +} | |
55 | + | |
43 | 56 | func (handler *ApiHandler) ServeHTTP( |
44 | 57 | response http.ResponseWriter, |
45 | 58 | request *http.Request, |
... | ... | @@ -65,10 +78,47 @@ func (handler *ApiHandler) ServeHTTP( |
65 | 78 | } |
66 | 79 | } |
67 | 80 | |
68 | -func router() { | |
69 | - handler := ApiHandler{} | |
81 | +func NewServer(addr string, log *logger.Logger) (server *Server) { | |
82 | + handler := ApiHandler{log: log} | |
70 | 83 | |
71 | 84 | http.Handle("/api/0.0.1/", http.StripPrefix("/api/0.0.1/", &handler)) |
85 | + | |
86 | + server = &Server{ | |
87 | + server: &http.Server{Addr: addr}, | |
88 | + log: log, | |
89 | + Stop: make(chan bool), | |
90 | + } | |
91 | + go func() { | |
92 | + server.log.Info("Listening on %s", addr) | |
93 | + if err := server.server.ListenAndServe(); | |
94 | + err != http.ErrServerClosed { | |
95 | + logger.Default.LogError(err, "Stop listening") | |
96 | + } | |
97 | + }() | |
98 | + | |
99 | + interrupt := make(chan os.Signal, 1) | |
100 | + signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) | |
101 | + go func() { | |
102 | + for run, ok := true, true; run && ok; { | |
103 | + select { | |
104 | + case <-interrupt: | |
105 | + server.log.Info("API service Interrupted by signal") | |
106 | + run = false | |
107 | + case run, ok = <-server.Stop: | |
108 | + server.log.Info("API service stopped") | |
109 | + } | |
110 | + } | |
111 | + | |
112 | + ctx := context.Background() | |
113 | + if err := server.server.Shutdown(ctx); err != nil { | |
114 | + server.log.LogError(err, "Unclean server shutdown") | |
115 | + } else { | |
116 | + server.log.Info("Server stopped") | |
117 | + } | |
118 | + server.Stop <- true | |
119 | + }() | |
120 | + | |
121 | + return | |
72 | 122 | } |
73 | 123 | |
74 | 124 | // vim: ts=4 sts=4 sw=4 noet tw=72: | ... | ... |
Please
register
or
login
to post a comment