generated from kzmake/skeleton
/
main.go
124 lines (99 loc) · 2.85 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
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"
userpb "github.com/kzmake/examples/basic-publish-and-subscribe-py/gen/go/basic/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 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")
}),
)
if err := userpb.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)
}
}