forked from johanbrandhorst/gopherjs-grpc-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
121 lines (104 loc) · 3.33 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"context"
"crypto/tls"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/Sirupsen/logrus"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/tmc/grpc-websocket-proxy/wsproxy"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"github.com/johanbrandhorst/gopherjs-grpc-websocket/client/compiled"
pserver "github.com/johanbrandhorst/gopherjs-grpc-websocket/protos/server"
"github.com/johanbrandhorst/gopherjs-grpc-websocket/server"
"github.com/johanbrandhorst/gopherjs-grpc-websocket/server/insecure"
)
var logger *logrus.Logger
// If you change this, you'll need to change the cert as well
const addr = "localhost:10000"
func init() {
logger = logrus.StandardLogger()
logrus.SetLevel(logrus.InfoLevel)
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
TimestampFormat: time.Kitchen,
DisableSorting: true,
})
grpclog.SetLogger(logger)
}
func main() {
s := &server.Server{}
gs := grpc.NewServer(grpc.Creds(credentials.NewServerTLSFromCert(insecure.KeyPair)))
pserver.RegisterMyServerServer(gs, s)
conn, err := net.Listen("tcp", addr)
if err != nil {
logger.WithError(err).Fatal("Failed to start listener")
}
// Create a context for easy cancellation
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
// Gracefully shut down on ctrl-c
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-c
go cancelFunc()
go gs.GracefulStop()
go conn.Close()
}()
mux := http.NewServeMux()
// Serve the gopherjs client
mux.Handle("/", http.FileServer(&assetfs.AssetFS{
Asset: compiled.Asset,
AssetDir: compiled.AssetDir,
AssetInfo: compiled.AssetInfo,
}))
gwMux := runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
EmitDefaults: true,
OrigName: true,
}),
)
// Wrap the gateway in the websocket proxy for bidi streams!
mux.Handle("/api/", wsproxy.WebsocketProxy(gwMux))
dcreds := credentials.NewTLS(&tls.Config{
ServerName: addr,
RootCAs: insecure.CertPool,
})
dopts := []grpc.DialOption{grpc.WithTransportCredentials(dcreds)}
err = pserver.RegisterMyServerHandlerFromEndpoint(ctx, gwMux, addr, dopts)
if err != nil {
logger.WithError(err).Fatal("Failed to dial server")
}
srv := &http.Server{
Addr: addr,
Handler: grpcHandlerFunc(gs, mux),
TLSConfig: &tls.Config{
NextProtos: []string{"h2"},
Certificates: []tls.Certificate{*insecure.KeyPair},
},
}
logger.Warn("Serving on https://", addr)
logger.Fatal(srv.Serve(tls.NewListener(conn, srv.TLSConfig)))
}
// GrpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
// connections or otherHandler otherwise. Copied from cockroachdb.
func grpcHandlerFunc(grpcServer http.Handler, otherHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This is a partial recreation of gRPC's internal checks https://github.com/grpc/grpc-go/pull/514/files#diff-95e9a25b738459a2d3030e1e6fa2a718R61
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
}
})
}