-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpub_server.go
59 lines (54 loc) · 1.36 KB
/
pub_server.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
package gosaqws
import (
"context"
"fmt"
"log"
"net/http"
"time"
)
// Server is a small wrapper around http.Server
//
// This wrapper provides just convenience functions to launch and shutdown (something that is forgotten
// in many applications) the webserver easily.
type Server struct {
srv *http.Server
}
// Launch returns a handle to the server
//
// The handle is needed to Shutdown the server later
func Launch(port int) (server Server) {
addr := fmt.Sprintf(":%d", port)
server.srv = &http.Server{Addr: addr}
go func() {
err := server.srv.ListenAndServe()
if err != nil {
log.Println("ERROR in http.Server.ListenAndServe:", err)
}
}()
return server
}
// Launch returns a handle to the server
//
// The handle is needed to Shutdown the server later
func LaunchTLS(port int, crtFile string, keyFile string) (server Server) {
addr := fmt.Sprintf(":%d", port)
server.srv = &http.Server{Addr: addr}
go func() {
err := server.srv.ListenAndServeTLS(crtFile, keyFile)
if err != nil {
log.Println("ERROR in http.Server.ListenAndServeTLS:", err)
}
}()
return server
}
func (server *Server) Shutdown() {
if server.srv != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := server.srv.Shutdown(ctx)
if err != nil {
log.Printf("Error while shutting down webserver")
}
server.srv = nil
}
}