-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_gateway.go
72 lines (60 loc) · 1.63 KB
/
main_gateway.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
package gateway
import (
"context"
"net/http"
"github.com/golang/glog"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
// Endpoint describes a gRPC endpoint
type Endpoint struct {
Network, Addr string
}
// Options is a set of options to be passed to Run
type Options struct {
// Addr is the address to listen
Addr string
// GRPCServer defines an endpoint of a gRPC service
GRPCServer Endpoint
// Mux is a list of options to be passed to the gRPC-Gateway multiplexer
Mux []gwruntime.ServeMuxOption
}
// Run starts a HTTP server and blocks while running if successful.
// The server will be shutdown when "ctx" is canceled.
func Run(ctx context.Context, opts Options) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
conn, err := dial(ctx, opts.GRPCServer.Network, opts.GRPCServer.Addr)
if err != nil {
return err
}
go func() {
<-ctx.Done()
if err := conn.Close(); err != nil {
glog.Errorf("Failed to close a client connection to the gRPC server: %v", err)
}
}()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", healthzServer(conn))
gw, err := newGateway(ctx, conn, opts.Mux)
if err != nil {
return err
}
mux.Handle("/", gw)
s := &http.Server{
Addr: opts.Addr,
Handler: allowCORS(mux),
}
go func() {
<-ctx.Done()
glog.Infof("Shutting down the http server")
if err := s.Shutdown(context.Background()); err != nil {
glog.Errorf("Failed to shutdown http server: %v", err)
}
}()
glog.Infof("Starting listening at %s", opts.Addr)
if err := s.ListenAndServe(); err != http.ErrServerClosed {
glog.Errorf("Failed to listen and serve: %v", err)
return err
}
return nil
}