-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
181 lines (154 loc) · 4.39 KB
/
run.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package cherry
import (
"context"
"fmt"
"github.com/hopeio/context/httpctx"
httpi "github.com/hopeio/utils/net/http"
"github.com/hopeio/utils/net/http/grpc/web"
stringsi "github.com/hopeio/utils/strings"
"github.com/quic-go/quic-go"
"github.com/rs/cors"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"net"
"net/http"
"os/signal"
"runtime/debug"
"strings"
"syscall"
"github.com/hopeio/utils/log"
"go.uber.org/zap"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc"
)
func (s *Server) Run() {
s.Init()
baseCtx := context.Background()
// Handle SIGINT (CTRL+C) gracefully.
sigCtx, stop := signal.NotifyContext(baseCtx, // kill -SIGINT XXXX 或 Ctrl+c
syscall.SIGINT, // register that too, it should be ok
// os.Kill等同于syscall.Kill
syscall.SIGKILL, // register that too, it should be ok
// kill -SIGTERM XXXX
syscall.SIGTERM,
)
defer stop()
if s.OnStart != nil {
s.OnStart(sigCtx)
}
grpcServer := s.grpcHandler()
httpHandler := s.httpHandler()
// cors
if s.EnableCors {
var corsServer *cors.Cors
if s.Cors == nil {
corsServer = cors.AllowAll()
} else {
corsServer = cors.New(*s.Cors)
}
httpHandler = corsServer.Handler(httpHandler).(http.HandlerFunc)
}
// grpc-web
var wrappedGrpc *web.WrappedGrpcServer
if s.EnableGrpcWeb {
wrappedGrpc = web.WrapServer(grpcServer, s.GrpcWebOptions...)
}
enableTelemetry := s.EnableTelemetry
//systemTracing := serviceConfig.SystemTracing
if enableTelemetry {
grpc.EnableTracing = true
// Set up OpenTelemetry.
otelShutdown, err := setupOTelSDK(sigCtx, &s.TelemetryConfig)
if err != nil {
log.Fatal(err)
}
// Handle shutdown properly so nothing leaks.
defer otelShutdown(sigCtx)
}
var handler http.Handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Errorw(fmt.Sprintf("panic: %v", err), zap.String(log.FieldStack, stringsi.BytesToString(debug.Stack())))
w.Header().Set(httpi.HeaderContentType, httpi.ContentJsonHeaderValue)
_, err := w.Write(httpi.ResponseSysErr)
if err != nil {
log.Error(err)
}
}
}()
// 简单的中间件支持
for _, middleware := range s.Middlewares {
middleware(w, r)
}
ctx := httpctx.FromRequest(httpctx.RequestCtx{Request: r, Response: w})
r = r.WithContext(ctx.Wrapper())
contentType := r.Header.Get(httpi.HeaderContentType)
if strings.HasPrefix(contentType, httpi.ContentGrpcHeaderValue) {
if strings.HasPrefix(contentType[len(httpi.ContentGrpcHeaderValue):], "-web") && wrappedGrpc != nil {
wrappedGrpc.ServeHTTP(w, r)
} else if r.ProtoMajor == 2 && grpcServer != nil {
grpcServer.ServeHTTP(w, r) // gRPC Server
}
} else {
httpHandler.ServeHTTP(w, r)
}
ctx.RootSpan().End()
})
if enableTelemetry {
http.DefaultClient = otelhttp.DefaultClient
/* handlerBack := handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//apiCounter.Add(r.Context(), 1)
attr := semconv.HTTPRouteKey.String(r.RequestURI)
span := trace.SpanFromContext(r.Context())
span.SetAttributes(attr)
labeler, _ := otelhttp.LabelerFromContext(r.Context())
labeler.Add(attr)
handlerBack.ServeHTTP(w, r)
})*/
handler = otelhttp.NewHandler(handler, "server")
}
server := &s.Http
server.BaseContext = func(_ net.Listener) context.Context {
return sigCtx
}
// 为了提供grpc服务,默认启用http2
h2Handler := h2c.NewHandler(handler, &s.Http2)
server.Handler = h2Handler
srvErr := make(chan error, 1)
if s.Http3 != nil && s.Http3.TLSConfig != nil {
s.Http3.Handler = handler
s.Http3.ConnContext = func(ctx context.Context, c quic.Connection) context.Context {
return sigCtx
}
go func() {
log.Infof("http3 listening: %s", s.Http3.Addr)
srvErr <- s.Http3.ListenAndServe()
}()
}
go func() {
log.Infof("listening: %s", s.Http.Addr)
srvErr <- server.ListenAndServe()
}()
// Wait for interruption.
select {
case err := <-srvErr:
// Error when starting HTTP server.
log.Fatalf("failed to serve: %v", err)
case <-sigCtx.Done():
// Wait for first CTRL+C.
// Stop receiving signal notifications as soon as possible.
stop()
log.Debug("stop server")
}
//服务关闭
if grpcServer != nil {
grpcServer.GracefulStop()
}
if err := server.Shutdown(context.Background()); err != nil {
log.Error(err)
}
if s.OnStop != nil {
s.OnStop(sigCtx)
}
}