-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
132 lines (107 loc) · 3.05 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"context"
"io"
"net/http"
"os"
"os/signal"
"syscall"
"time"
ginlogger "github.com/gin-contrib/logger"
"github.com/gin-gonic/gin"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/kelseyhightower/envconfig"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/encoding/protojson"
pb "github.com/kzmake/_akka-grpc-with-dapr/gateway/zz_generated/go/agwd/user/v1"
)
type Env struct {
GateawayAddress string `default:"0.0.0.0:8080"`
ServiceAddress string `default:"localhost:50001"`
}
const prefix = "GATEWAY"
var env Env
func init() {
if err := envconfig.Process(prefix, &env); err != nil {
log.Fatal().Msgf("%+v", err)
}
log.Debug().Msgf("%+v", env)
}
func newGatewayServer(ctx context.Context) (*http.Server, error) {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(ginlogger.SetLogger(
ginlogger.WithLogger(func(c *gin.Context, _ io.Writer, latency time.Duration) zerolog.Logger {
return log.Logger.With().
Timestamp().
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Str("path", c.Request.URL.Path).
Str("ip", c.ClientIP()).
Dur("latency", latency).
Str("user_agent", c.Request.UserAgent()).
Logger()
}),
ginlogger.WithSkipPath([]string{"/healthz"}),
))
r.Use(gin.Recovery())
mux := runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
Marshaler: &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
},
}),
runtime.WithMetadata(func(_ context.Context, _ *http.Request) metadata.MD {
return metadata.Pairs("dapr-app-id", "user")
}),
)
if err := pb.RegisterUserServiceHandlerFromEndpoint(ctx, mux, env.ServiceAddress, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
return nil, xerrors.Errorf("Failed to register handler: %w", err)
}
r.Any("/*any", gin.WrapH(mux))
return &http.Server{Addr: env.GateawayAddress, Handler: r}, nil
}
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
gatewayS, err := newGatewayServer(ctx)
if err != nil {
log.Fatal().Msgf("Failed to build gateway server: %v", err)
}
g.Go(func() error { return gatewayS.ListenAndServe() })
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(quit)
select {
case <-quit:
break
case <-ctx.Done():
break
}
cancel()
log.Info().Msg("Shutting down server...")
ctx, timeout := context.WithTimeout(context.Background(), 5*time.Second)
defer timeout()
if err := gatewayS.Shutdown(ctx); err != nil {
return xerrors.Errorf("failed to shutdown: %w", err)
}
log.Info().Msgf("Server exiting")
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal().Msgf("Failed to run server: %v", err)
}
}