Skip to content

Commit 1bfb0a2

Browse files
lunny6543
andauthored
Refactor routers directory (#15800)
* refactor routers directory * move func used for web and api to common * make corsHandler a function to prohibit side efects * rm unused func Co-authored-by: 6543 <[email protected]>
1 parent e03a91a commit 1bfb0a2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+940
-800
lines changed

.golangci.yml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,6 @@ issues:
7070
- path: modules/log/
7171
linters:
7272
- errcheck
73-
- path: routers/routes/web.go
74-
linters:
75-
- dupl
7673
- path: routers/api/v1/repo/issue_subscription.go
7774
linters:
7875
- dupl
@@ -114,3 +111,4 @@ issues:
114111
linters:
115112
- staticcheck
116113
text: "svc.IsAnInteractiveSession is deprecated: Use IsWindowsService instead."
114+

cmd/web.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import (
1717
"code.gitea.io/gitea/modules/log"
1818
"code.gitea.io/gitea/modules/setting"
1919
"code.gitea.io/gitea/routers"
20-
"code.gitea.io/gitea/routers/routes"
20+
"code.gitea.io/gitea/routers/install"
2121

2222
context2 "github.com/gorilla/context"
2323
"github.com/urfave/cli"
@@ -88,7 +88,7 @@ func runWeb(ctx *cli.Context) error {
8888
}
8989

9090
// Perform pre-initialization
91-
needsInstall := routers.PreInstallInit(graceful.GetManager().HammerContext())
91+
needsInstall := install.PreloadSettings(graceful.GetManager().HammerContext())
9292
if needsInstall {
9393
// Flag for port number in case first time run conflict
9494
if ctx.IsSet("port") {
@@ -101,7 +101,7 @@ func runWeb(ctx *cli.Context) error {
101101
return err
102102
}
103103
}
104-
c := routes.InstallRoutes()
104+
c := install.Routes()
105105
err := listen(c, false)
106106
select {
107107
case <-graceful.GetManager().IsShutdown():
@@ -134,7 +134,7 @@ func runWeb(ctx *cli.Context) error {
134134
}
135135

136136
// Set up Chi routes
137-
c := routes.NormalRoutes()
137+
c := routers.NormalRoutes()
138138
err := listen(c, true)
139139
<-graceful.GetManager().Done()
140140
log.Info("PID: %d Gitea Web Finished", os.Getpid())

contrib/pr/checkout.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ import (
3131
"code.gitea.io/gitea/modules/setting"
3232
"code.gitea.io/gitea/modules/util"
3333
"code.gitea.io/gitea/routers"
34-
"code.gitea.io/gitea/routers/routes"
3534

3635
"github.com/go-git/go-git/v5"
3736
"github.com/go-git/go-git/v5/config"
@@ -116,7 +115,7 @@ func runPR() {
116115
//routers.GlobalInit()
117116
external.RegisterRenderers()
118117
markup.Init()
119-
c := routes.NormalRoutes()
118+
c := routers.NormalRoutes()
120119

121120
log.Printf("[PR] Ready for testing !\n")
122121
log.Printf("[PR] Login with user1, user2, user3, ... with pass: password\n")

integrations/create_no_session_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import (
1414

1515
"code.gitea.io/gitea/modules/setting"
1616
"code.gitea.io/gitea/modules/util"
17-
"code.gitea.io/gitea/routers/routes"
17+
"code.gitea.io/gitea/routers"
1818

1919
"gitea.com/go-chi/session"
2020
jsoniter "github.com/json-iterator/go"
@@ -58,7 +58,7 @@ func TestSessionFileCreation(t *testing.T) {
5858
oldSessionConfig := setting.SessionConfig.ProviderConfig
5959
defer func() {
6060
setting.SessionConfig.ProviderConfig = oldSessionConfig
61-
c = routes.NormalRoutes()
61+
c = routers.NormalRoutes()
6262
}()
6363

6464
var config session.Options
@@ -84,7 +84,7 @@ func TestSessionFileCreation(t *testing.T) {
8484

8585
setting.SessionConfig.ProviderConfig = string(newConfigBytes)
8686

87-
c = routes.NormalRoutes()
87+
c = routers.NormalRoutes()
8888

8989
t.Run("NoSessionOnViewIssue", func(t *testing.T) {
9090
defer PrintCurrentTest(t)()

integrations/integration_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ import (
3434
"code.gitea.io/gitea/modules/util"
3535
"code.gitea.io/gitea/modules/web"
3636
"code.gitea.io/gitea/routers"
37-
"code.gitea.io/gitea/routers/routes"
3837

3938
"github.com/PuerkitoBio/goquery"
4039
jsoniter "github.com/json-iterator/go"
@@ -88,7 +87,7 @@ func TestMain(m *testing.M) {
8887
defer cancel()
8988

9089
initIntegrationTest()
91-
c = routes.NormalRoutes()
90+
c = routers.NormalRoutes()
9291

9392
// integration test settings...
9493
if setting.Cfg != nil {

integrations/lfs_getobject_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"code.gitea.io/gitea/models"
1616
"code.gitea.io/gitea/modules/lfs"
1717
"code.gitea.io/gitea/modules/setting"
18-
"code.gitea.io/gitea/routers/routes"
18+
"code.gitea.io/gitea/routers/web"
1919

2020
jsoniter "github.com/json-iterator/go"
2121
gzipp "github.com/klauspost/compress/gzip"
@@ -99,7 +99,7 @@ func TestGetLFSLarge(t *testing.T) {
9999
t.Skip()
100100
return
101101
}
102-
content := make([]byte, routes.GzipMinSize*10)
102+
content := make([]byte, web.GzipMinSize*10)
103103
for i := range content {
104104
content[i] = byte(i % 256)
105105
}
@@ -115,7 +115,7 @@ func TestGetLFSGzip(t *testing.T) {
115115
t.Skip()
116116
return
117117
}
118-
b := make([]byte, routes.GzipMinSize*10)
118+
b := make([]byte, web.GzipMinSize*10)
119119
for i := range b {
120120
b[i] = byte(i % 256)
121121
}
@@ -136,7 +136,7 @@ func TestGetLFSZip(t *testing.T) {
136136
t.Skip()
137137
return
138138
}
139-
b := make([]byte, routes.GzipMinSize*10)
139+
b := make([]byte, web.GzipMinSize*10)
140140
for i := range b {
141141
b[i] = byte(i % 256)
142142
}

routers/api/v1/repo/file.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import (
1717
"code.gitea.io/gitea/modules/repofiles"
1818
api "code.gitea.io/gitea/modules/structs"
1919
"code.gitea.io/gitea/modules/web"
20-
"code.gitea.io/gitea/routers/repo"
20+
"code.gitea.io/gitea/routers/common"
2121
)
2222

2323
// GetRawFile get a file by path on a repository
@@ -83,7 +83,7 @@ func GetRawFile(ctx *context.APIContext) {
8383
}
8484
return
8585
}
86-
if err = repo.ServeBlob(ctx.Context, blob); err != nil {
86+
if err = common.ServeBlob(ctx.Context, blob); err != nil {
8787
ctx.Error(http.StatusInternalServerError, "ServeBlob", err)
8888
}
8989
}
@@ -126,7 +126,7 @@ func GetArchive(ctx *context.APIContext) {
126126
ctx.Repo.GitRepo = gitRepo
127127
defer gitRepo.Close()
128128

129-
repo.Download(ctx.Context)
129+
common.Download(ctx.Context)
130130
}
131131

132132
// GetEditorconfig get editor config of a repository

routers/common/db.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package common
6+
7+
import (
8+
"context"
9+
"fmt"
10+
"time"
11+
12+
"code.gitea.io/gitea/models"
13+
"code.gitea.io/gitea/models/migrations"
14+
"code.gitea.io/gitea/modules/log"
15+
"code.gitea.io/gitea/modules/setting"
16+
)
17+
18+
// InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology
19+
func InitDBEngine(ctx context.Context) (err error) {
20+
log.Info("Beginning ORM engine initialization.")
21+
for i := 0; i < setting.Database.DBConnectRetries; i++ {
22+
select {
23+
case <-ctx.Done():
24+
return fmt.Errorf("Aborted due to shutdown:\nin retry ORM engine initialization")
25+
default:
26+
}
27+
log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
28+
if err = models.NewEngine(ctx, migrations.Migrate); err == nil {
29+
break
30+
} else if i == setting.Database.DBConnectRetries-1 {
31+
return err
32+
}
33+
log.Error("ORM engine initialization attempt #%d/%d failed. Error: %v", i+1, setting.Database.DBConnectRetries, err)
34+
log.Info("Backing off for %d seconds", int64(setting.Database.DBConnectBackoff/time.Second))
35+
time.Sleep(setting.Database.DBConnectBackoff)
36+
}
37+
models.HasEngine = true
38+
return nil
39+
}

routers/common/logger.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package common
6+
7+
import (
8+
"net/http"
9+
"time"
10+
11+
"code.gitea.io/gitea/modules/context"
12+
"code.gitea.io/gitea/modules/log"
13+
)
14+
15+
// LoggerHandler is a handler that will log the routing to the default gitea log
16+
func LoggerHandler(level log.Level) func(next http.Handler) http.Handler {
17+
return func(next http.Handler) http.Handler {
18+
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
19+
start := time.Now()
20+
21+
_ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(req.Method), req.URL.RequestURI(), req.RemoteAddr)
22+
23+
next.ServeHTTP(w, req)
24+
25+
var status int
26+
if v, ok := w.(context.ResponseWriter); ok {
27+
status = v.Status()
28+
}
29+
30+
_ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(req.Method), req.URL.RequestURI(), log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(status)), log.ColoredTime(time.Since(start)))
31+
})
32+
}
33+
}

routers/common/middleware.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package common
6+
7+
import (
8+
"fmt"
9+
"net/http"
10+
"strings"
11+
12+
"code.gitea.io/gitea/modules/context"
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
16+
"github.com/chi-middleware/proxy"
17+
"github.com/go-chi/chi/middleware"
18+
)
19+
20+
// Middlewares returns common middlewares
21+
func Middlewares() []func(http.Handler) http.Handler {
22+
var handlers = []func(http.Handler) http.Handler{
23+
func(next http.Handler) http.Handler {
24+
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
25+
next.ServeHTTP(context.NewResponse(resp), req)
26+
})
27+
},
28+
}
29+
30+
if setting.ReverseProxyLimit > 0 {
31+
opt := proxy.NewForwardedHeadersOptions().
32+
WithForwardLimit(setting.ReverseProxyLimit).
33+
ClearTrustedProxies()
34+
for _, n := range setting.ReverseProxyTrustedProxies {
35+
if !strings.Contains(n, "/") {
36+
opt.AddTrustedProxy(n)
37+
} else {
38+
opt.AddTrustedNetwork(n)
39+
}
40+
}
41+
handlers = append(handlers, proxy.ForwardedHeaders(opt))
42+
}
43+
44+
handlers = append(handlers, middleware.StripSlashes)
45+
46+
if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
47+
if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
48+
handlers = append(handlers, LoggerHandler(setting.RouterLogLevel))
49+
}
50+
}
51+
if setting.EnableAccessLog {
52+
handlers = append(handlers, context.AccessLogger())
53+
}
54+
55+
handlers = append(handlers, func(next http.Handler) http.Handler {
56+
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
57+
// Why we need this? The Recovery() will try to render a beautiful
58+
// error page for user, but the process can still panic again, and other
59+
// middleware like session also may panic then we have to recover twice
60+
// and send a simple error page that should not panic any more.
61+
defer func() {
62+
if err := recover(); err != nil {
63+
combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2)))
64+
log.Error("%v", combinedErr)
65+
if setting.IsProd() {
66+
http.Error(resp, http.StatusText(500), 500)
67+
} else {
68+
http.Error(resp, combinedErr, 500)
69+
}
70+
}
71+
}()
72+
next.ServeHTTP(resp, req)
73+
})
74+
})
75+
return handlers
76+
}

0 commit comments

Comments
 (0)