generated from kzmake/skeleton
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
148 lines (120 loc) · 3.45 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package main
import (
"context"
"io"
"net/http"
"os"
"os/signal"
"strconv"
"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/proto"
pb "github.com/kzmake/examples/basic-state-management/gen/go/user/v1"
)
type Env struct {
Address string `default:"0.0.0.0:8080"`
Dapr struct {
Address string `default:"localhost:50001"`
}
}
const prefix = "GATEWAY"
var env Env
func init() {
log.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
if err := envconfig.Process(prefix, &env); err != nil {
log.Fatal().Msgf("%+v", err)
}
log.Debug().Msgf("%+v", env)
}
func httpResponseModifier(ctx context.Context, w http.ResponseWriter, p proto.Message) error {
md, ok := runtime.ServerMetadataFromContext(ctx)
if !ok {
return nil
}
// set http status code
if vals := md.HeaderMD.Get("x-http-code"); len(vals) > 0 {
code, err := strconv.Atoi(vals[0])
if err != nil {
return err
}
// delete the headers to not expose any grpc-metadata in http response
delete(md.HeaderMD, "x-http-code")
delete(w.Header(), "Grpc-Metadata-X-Http-Code")
w.WriteHeader(code)
}
return nil
}
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())
userMux := runtime.NewServeMux(
runtime.WithMetadata(func(_ context.Context, _ *http.Request) metadata.MD {
return metadata.Pairs("dapr-app-id", "svc-user")
}),
runtime.WithForwardResponseOption(httpResponseModifier),
)
if err := pb.RegisterUserServiceHandlerFromEndpoint(ctx, userMux, env.Dapr.Address, []grpc.DialOption{grpc.WithInsecure()}); err != nil {
return nil, xerrors.Errorf("Failed to register handler: %w", err)
}
r.Group("/user/v1").Any("/*any", gin.WrapH(userMux))
return &http.Server{Addr: env.Address, 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)
}
}