-
Notifications
You must be signed in to change notification settings - Fork 62
/
new.go
162 lines (139 loc) · 5.04 KB
/
new.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
// SPDX-License-Identifier: AGPL-3.0-only
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
package web
import (
"errors"
"fmt"
"net/http"
"net/http/pprof"
"strconv"
"strings"
"time"
"github.com/bytedance/sonic"
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/utils"
"github.com/uber-go/tally/v4"
promreporter "github.com/uber-go/tally/v4/prometheus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/bangumi/server/internal/config"
"github.com/bangumi/server/internal/config/env"
"github.com/bangumi/server/internal/metrics"
"github.com/bangumi/server/internal/pkg/errgo"
"github.com/bangumi/server/internal/pkg/gtime"
"github.com/bangumi/server/internal/pkg/logger"
"github.com/bangumi/server/internal/pkg/random"
"github.com/bangumi/server/internal/web/middleware/recovery"
"github.com/bangumi/server/internal/web/req/cf"
"github.com/bangumi/server/internal/web/res"
"github.com/bangumi/server/internal/web/util"
)
const headerProcessTime = "x-process-time-ms"
const headerServerVersion = "x-server-version"
func New(scope tally.Scope, reporter promreporter.Reporter) *fiber.App {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
StrictRouting: true,
CaseSensitive: true,
ErrorHandler: getDefaultErrorHandler(),
JSONEncoder: sonic.Marshal,
})
count := scope.Counter("request_count_total")
histogram := scope.Histogram("response_time", metrics.ResponseTimeBucket())
app.Use(func(c *fiber.Ctx) error {
count.Inc(1)
start := time.Now()
err := c.Next()
sub := time.Since(start)
histogram.RecordDuration(sub)
c.Set(headerProcessTime, strconv.FormatInt(sub.Milliseconds(), 10))
c.Set(headerServerVersion, config.Version)
return err
})
if env.Development {
app.Use(func(c *fiber.Ctx) error {
devRequestID := "fake-ray-" + random.Base62String(10)
c.Request().Header.Set(cf.HeaderRequestID, devRequestID)
c.Request().Header.Set(cf.HeaderRequestIP, c.Context().RemoteIP().String())
c.Set(cf.HeaderRequestID, devRequestID)
return c.Next()
})
app.Use(cors.New(cors.Config{
MaxAge: gtime.OneWeekSec,
ExposeHeaders: strings.Join([]string{headerProcessTime, headerServerVersion, cf.HeaderRequestID}, ","),
}))
}
app.Use(recovery.New())
app.Get("/metrics", adaptor.HTTPHandler(reporter.HTTPHandler()))
addProfile(app)
if env.Development {
app.Use("/openapi/", openapiHandler)
}
return app
}
func addProfile(app *fiber.App) {
app.Get("/debug/pprof/cmdline", adaptor.HTTPHandlerFunc(pprof.Cmdline))
app.Get("/debug/pprof/profile", adaptor.HTTPHandlerFunc(pprof.Profile))
app.Get("/debug/pprof/symbol", adaptor.HTTPHandlerFunc(pprof.Symbol))
app.Get("/debug/pprof/trace", adaptor.HTTPHandlerFunc(pprof.Trace))
app.Use("/debug/pprof/", adaptor.HTTPHandlerFunc(pprof.Index))
}
func Start(c config.AppConfig, app *fiber.App) error {
addr := c.ListenAddr()
logger.Infoln("http server listening at", addr)
if env.Development {
fmt.Printf("\nvisit http://%s/\n\n", strings.ReplaceAll(addr, "0.0.0.0", "127.0.0.1"))
}
return errgo.Wrap(app.Listen(c.ListenAddr()), "fiber.App.Listen")
}
func getDefaultErrorHandler() func(*fiber.Ctx, error) error {
var log = logger.Named("http.err").
WithOptions(zap.AddStacktrace(zapcore.PanicLevel), zap.WithCaller(false))
return func(ctx *fiber.Ctx, err error) error {
var e res.HTTPError
if errors.As(err, &e) {
// handle expected http error
return res.JSON(ctx.Status(e.Code), res.Error{
Title: utils.StatusMessage(e.Code),
Description: e.Msg,
Details: util.Detail(ctx),
})
}
//nolint:forbidigo,errorlint
if fErr, ok := err.(*fiber.Error); ok {
log.Error("unexpected fiber error",
zap.Int("code", fErr.Code),
zap.String("message", fErr.Message),
zap.String("path", ctx.Path()),
zap.ByteString("query", ctx.Request().URI().QueryString()),
zap.String("cf-ray", ctx.Get(cf.HeaderRequestID)),
)
return res.JSON(ctx.Status(http.StatusInternalServerError), res.Error{
Title: utils.StatusMessage(fErr.Code),
Description: fErr.Message,
Details: util.DetailWithErr(ctx, err),
})
}
log.Error("unexpected error",
zap.Error(err),
zap.String("path", ctx.Path()),
zap.ByteString("query", ctx.Request().URI().QueryString()),
zap.String("cf-ray", ctx.Get(cf.HeaderRequestID)),
)
// unexpected error, return internal server error
return res.InternalError(ctx, err, "Unexpected Internal Server Error")
}
}