-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc-proxy.go
157 lines (133 loc) · 4.34 KB
/
grpc-proxy.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main
import (
"carou-gateway/extras"
_ "carou-gateway/protos"
"encoding/json"
"errors"
"fmt"
"github.com/carousell/go-utils/ctxutils"
proto2 "github.com/golang/protobuf/proto"
"github.com/mwitkow/grpc-proxy/proxy"
"golang.org/x/net/context"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"time"
)
func main() {
configurationFile := "./config.json"
args := os.Args[1:]
if len(args) > 0 {
configurationFile = args[0]
}
config := extras.GetConfiguration(configurationFile)
listen := ":50051"
if config.Listen != "" {
listen = config.Listen
}
lis, err := net.Listen("tcp", listen)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
//grpcServ := grpc.NewServer()
httpMux := http.NewServeMux()
httpMux.HandleFunc("/", home)
fmt.Printf("Proxy running at %q\n", listen)
server := GetServer(config)
//if err := server.Serve(lis); err != nil {
// log.Fatalf("failed to serve: %v", err)
//}
mixedHandler := newHTTPandGRPCMux(httpMux, server)
http2Server := &http2.Server{}
http1Server := &http.Server{Handler: h2c.NewHandler(mixedHandler, http2Server)}
if err != nil {
panic(err)
}
err = http1Server.Serve(lis)
if errors.Is(err, http.ErrServerClosed) {
fmt.Println("server closed")
} else if err != nil {
panic(err)
}
}
func home(w http.ResponseWriter, request *http.Request) {
requestURI := request.RequestURI
method := request.Method
body := request.Body
backendDetails := getBackendServerDetails(requestURI)
outgoingMethodName := backendDetails.OutGoingMethodName
requestProto := backendDetails.RequestProtoType
responseProto := backendDetails.ResponseProtoType
serverDetails := backendDetails.Backend
timeout := backendDetails.Timeout
//decoder := json.NewDecoder(request.Body)
bytes, err := ioutil.ReadAll(request.Body)
pbtype, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(requestProto))
fmt.Println(pbtype)
msg := proto2.MessageV1(pbtype.New().Interface())
json.Unmarshal(bytes, msg)
conn, err := grpc.DialContext(ctxutils.NewBackgroundContext(context.Background()), serverDetails,
grpc.WithInsecure(),
grpc.WithTimeout(time.Duration(timeout)*time.Millisecond))
outputType, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(responseProto))
output := proto2.MessageV1(outputType.New().Interface())
err1 := grpc.Invoke(context.Background(), outgoingMethodName, msg, output, conn)
if err != nil || err1 != nil{
fmt.Println(err)
}
fmt.Println("uri: ", requestURI)
fmt.Println("method: ", method)
fmt.Println("body: ", body)
fmt.Fprintf(w, "", output)
}
func newHTTPandGRPCMux(httpHand http.Handler, grpcHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("content-type"), "application/grpc") {
grpcHandler.ServeHTTP(w, r)
return
}
httpHand.ServeHTTP(w, r)
})
}
type HttpHandler struct{}
// implement `ServeHTTP` method on `HttpHandler` struct
func (h HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
// create response binary data
data := []byte("Hello World!") // slice of bytes
// write `data` to response
res.Write(data)
}
func GetServer (config extras.Config) *grpc.Server {
var opts []grpc.ServerOption
opts = append(opts, grpc.CustomCodec(proxy.Codec()),
grpc.UnknownServiceHandler(proxy.TransparentHandler(extras.GetDirector(config))))
//if config.CertFile != "" && config.KeyFile != "" {
// creds, err := credentials.NewServerTLSFromFile(config.CertFile, config.KeyFile)
// if err != nil {
// grpclog.Fatalf("Failed to generate credentials %v", err)
// }
// opts = append(opts, grpc.Creds(creds))
//}
return grpc.NewServer(opts...)
}
func getBackendServerDetails(incomingURI string) extras.Backend {
configurationFile := "./config.json"
config := extras.GetConfiguration(configurationFile)
for _, backend := range config.Backends {
if strings.HasPrefix(incomingURI, backend.Filter) {
return backend
}
}
return extras.Backend{}
}
func validateUser() bool {
return true
}