/
main.go
54 lines (47 loc) · 1.41 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
package main
import (
"context"
"log"
"net"
"net/http"
"github.com/felixge/httpsnoop"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
v1 "github.com/marcosdias/tutorial-grpc-rest-api-go/gen/product/v1"
"github.com/marcosdias/tutorial-grpc-rest-api-go/server"
"github.com/soheilhy/cmux"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/reflection"
)
func main() {
grpcServer := grpc.NewServer()
srv := server.New()
v1.RegisterProductServiceServer(grpcServer, srv)
reflection.Register(grpcServer)
ctx := context.Background()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
err := v1.RegisterProductServiceHandlerFromEndpoint(ctx, mux, "localhost:8081", opts)
if err != nil {
log.Fatal(err)
}
server := http.Server{
Handler: withLogger(mux),
}
listener, err := net.Listen("tcp", ":8081")
if err != nil {
log.Fatal(err)
}
multiplexer := cmux.New(listener)
httpL := multiplexer.Match(cmux.HTTP1Fast())
grpcL := multiplexer.Match(cmux.HTTP2())
go server.Serve(httpL)
go grpcServer.Serve(grpcL)
multiplexer.Serve()
}
func withLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
m := httpsnoop.CaptureMetrics(handler, writer, request)
log.Printf("http[%d]-- %s -- %s\n", m.Code, m.Duration, request.URL.Path)
})
}