-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.go
85 lines (71 loc) · 2.02 KB
/
main.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
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"github.com/tarndt/wasmws"
)
//go:generate ./build.bash
type helloServer struct{}
func (*helloServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
//App context setup
appCtx, appCancel := context.WithCancel(context.Background())
defer appCancel()
//Setup HTTP / Websocket server
router := http.NewServeMux()
wsl := wasmws.NewWebSocketListener(appCtx)
router.HandleFunc("/grpc-proxy", wsl.ServeHTTP)
router.Handle("/", http.FileServer(http.Dir("./static")))
httpServer := &http.Server{Addr: ":8080", Handler: router}
//Run HTTP server
go func() {
defer appCancel()
log.Printf("ERROR: HTTP Listen and Server failed; Details: %s", httpServer.ListenAndServe())
}()
//gRPC setup
creds, err := credentials.NewServerTLSFromFile("cert.pem", "key.pem")
if err != nil {
log.Fatalf("Failed to contruct gRPC TSL credentials from {cert,key}.pem: %s", err)
}
grpcServer := grpc.NewServer(grpc.Creds(creds))
pb.RegisterGreeterServer(grpcServer, new(helloServer))
//Run gRPC server
go func() {
defer appCancel()
if err := grpcServer.Serve(wsl); err != nil {
log.Printf("ERROR: Failed to serve gRPC connections; Details: %s", err)
}
}()
//Handle signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
log.Printf("INFO: Received shutdown signal: %s", <-sigs)
appCancel()
}()
//Shutdown
<-appCtx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*2)
defer shutdownCancel()
grpcShutdown := make(chan struct{}, 1)
go func() {
grpcServer.GracefulStop()
grpcShutdown <- struct{}{}
}()
httpServer.Shutdown(shutdownCtx)
select {
case <-grpcShutdown:
case <-shutdownCtx.Done():
grpcServer.Stop()
}
}