-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (70 loc) · 1.97 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
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"strings"
"context"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
cert "grpc-go-server-example/cert"
pb "grpc-go-server-example/grpcserver"
server "grpc-go-server-example/grpcsimpleserver"
grpc "google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
host = "localhost"
port = "50051"
)
var defaultAddress = host + ":" + port
func main() {
opts := []grpc.ServerOption{
grpc.Creds(credentials.NewClientTLSFromCert(cert.DemoCertPool, defaultAddress))}
grpcServer := grpc.NewServer(opts...)
fibonacciService := server.CreateServer()
pb.RegisterFibonacciServiceServer(grpcServer, &fibonacciService)
ctx := context.Background()
dcreds := credentials.NewTLS(&tls.Config{
ServerName: defaultAddress,
RootCAs: cert.DemoCertPool,
InsecureSkipVerify: true,
})
dopts := []grpc.DialOption{grpc.WithTransportCredentials(dcreds)}
mux := http.NewServeMux()
gwmux := runtime.NewServeMux()
err := pb.RegisterFibonacciServiceHandlerFromEndpoint(ctx, gwmux, defaultAddress, dopts)
if err != nil {
fmt.Printf("serve: %v\n", err)
return
}
mux.Handle("/", gwmux)
conn, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
if err != nil {
panic(err)
}
srv := &http.Server{
Addr: defaultAddress,
Handler: grpcHandlerFunc(grpcServer, mux),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{*cert.DemoKeyPair},
NextProtos: []string{"h2"},
},
}
fmt.Printf("grpc on port: %v\n", port)
err = srv.Serve(tls.NewListener(conn, srv.TLSConfig))
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
return
}
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
}
})
}