forked from kyleconroy/grpc-on-heroku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
111 lines (91 loc) · 2.32 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
package main
import (
"io/ioutil"
"log"
"net"
"net/http"
"os"
"github.com/gengo/grpc-gateway/runtime"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
hw "github.com/kyleconroy/grpc-heroku/helloworld"
)
type server struct{}
func RequestSourceDestinition(ctx context.Context) string {
income, ok := peer.FromContext(ctx)
if ok {
return income.Addr.String()
}
return "error"
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *hw.HelloRequest) (*hw.HelloReply, error) {
return &hw.HelloReply{Message: RequestSourceDestinition(ctx)}, nil
}
func startGRPC(port string) error {
lis, err := net.Listen("tcp", ":"+port)
if err != nil {
return err
}
s := grpc.NewServer()
hw.RegisterGreeterServer(s, &server{})
return s.Serve(lis)
}
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Set(w, AccessControl{
Origin: "*",
AllowedMethods: []string{"GET", "HEAD", "OPTIONS", "POST", "PUT", "DELETE", "PATCH"},
})
next.ServeHTTP(w, r)
})
}
func startHTTP(httpPort, grpcPort string) error {
schema, err := ioutil.ReadFile("helloworld/helloworld.swagger.json")
if err != nil {
return err
}
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
gwmux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
if err := hw.RegisterGreeterHandlerFromEndpoint(ctx, gwmux, "127.0.0.1:"+grpcPort, opts); err != nil {
return err
}
mux := http.NewServeMux()
mux.HandleFunc("/v1/helloworld/greeter/swagger", func(w http.ResponseWriter, r *http.Request) {
Set(w, ContentType("application/json"))
w.WriteHeader(http.StatusOK)
w.Write(schema)
})
mux.Handle("/v1/", gwmux)
mux.Handle("/", http.FileServer(http.Dir("swagger-ui")))
http.ListenAndServe(":"+httpPort, cors(mux))
return nil
}
func main() {
errors := make(chan error)
httpPort := os.Getenv("PORT")
if httpPort == "" {
httpPort = "8080"
}
grpcPort := os.Getenv("GRPC_PORT")
if grpcPort == "" {
grpcPort = "50080"
}
if grpcPort == httpPort {
panic("Can't listen on the same port")
}
go func() {
errors <- startGRPC(grpcPort)
}()
go func() {
errors <- startHTTP(httpPort, grpcPort)
}()
for err := range errors {
log.Fatal(err)
return
}
}