-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
http-server.go
77 lines (69 loc) · 1.87 KB
/
http-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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package utils
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/gorilla/mux"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
// StartServer starts a HTTP or HTTP2 server
func StartServer(port int, appRouter func() *mux.Router, allowHTTP2 bool) {
// HTTP/2 is allowed only if the DAPR_TESTS_HTTP2 env var is set
if allowHTTP2 {
allowHTTP2, _ = strconv.ParseBool(os.Getenv("DAPR_TESTS_HTTP2"))
}
// Create a listener
addr := fmt.Sprintf(":%d", port)
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("Failed to create listener: %v", err)
}
var server *http.Server
if allowHTTP2 {
// Create a server capable of supporting HTTP2 Cleartext connections
// Also supports HTTP1.1 and upgrades from HTTP1.1 to HTTP2
h2s := &http2.Server{}
server = &http.Server{
Addr: addr,
Handler: h2c.NewHandler(appRouter(), h2s),
ConnState: func(c net.Conn, cs http.ConnState) {
// TODO: MAKE OPTIONAL
log.Printf("ConnState changed: %s -> %s state: %s", c.RemoteAddr(), c.LocalAddr(), cs)
},
}
} else {
server = &http.Server{
Addr: addr,
Handler: appRouter(),
ConnState: func(c net.Conn, cs http.ConnState) {
// TODO: MAKE OPTIONAL
log.Printf("ConnState changed: %s -> %s state: %s", c.RemoteAddr(), c.LocalAddr(), cs)
},
}
}
// Stop the server when we get a termination signal
stopCh := make(chan os.Signal, 1)
signal.Notify(stopCh, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGINT)
go func() {
// Wait for cancelation signal
<-stopCh
log.Println("Shutdown signal received")
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
server.Shutdown(ctx)
}()
// Blocking call
err = server.Serve(ln)
if err != http.ErrServerClosed {
log.Fatalf("Failed to run server: %v", err)
}
log.Println("Server shut down")
}