-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (54 loc) · 1.34 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
package main
import (
"context"
"net"
"net/http"
"sync"
"golang.org/x/net/http2"
"flag"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/nporsche/grpc_http_gw/server"
"github.com/nporsche/grpc_http_gw/userapi"
"google.golang.org/grpc"
)
var (
grpcAddr = flag.String("grpc-addr", "127.0.0.1:10000", "grpc serving address")
grpcGatewayAddr = flag.String("grpc-gw-addr", "127.0.0.1:10001", "grpc gw serving address")
wg sync.WaitGroup
)
func main() {
flag.Parse()
wg.Add(2)
go launchGrpcServer(*grpcAddr)
go launchGrpcGatewayServer(*grpcAddr, *grpcGatewayAddr)
wg.Wait()
}
func launchGrpcServer(addr string) {
defer wg.Done()
grpcServer := grpc.NewServer()
userapi.RegisterUserApiServer(grpcServer, &server.UserHandler{})
lsner, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
}
srv := &http2.Server{}
for {
conn, err := lsner.Accept()
if err != nil {
panic(err)
}
go func() {
opts := &http2.ServeConnOpts{Handler: grpcServer}
srv.ServeConn(conn, opts)
}()
}
}
func launchGrpcGatewayServer(grpcAddr string, gateway string) {
defer wg.Done()
gwmux := runtime.NewServeMux()
err := userapi.RegisterUserApiHandlerFromEndpoint(context.Background(), gwmux, grpcAddr, []grpc.DialOption{grpc.WithInsecure()})
if err != nil {
panic(err)
}
http.ListenAndServe(gateway, gwmux)
}