Skip to content

Commit d97b688

Browse files
committed
Refactor routers directory
1 parent b3ef6a6 commit d97b688

Some content is hidden

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

100 files changed

+721
-540
lines changed

cmd/web.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ 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"
21+
"code.gitea.io/gitea/routers/web"
2122

2223
context2 "github.com/gorilla/context"
2324
"github.com/urfave/cli"
@@ -88,7 +89,7 @@ func runWeb(ctx *cli.Context) error {
8889
}
8990

9091
// Perform pre-initialization
91-
needsInstall := routers.PreInstallInit(graceful.GetManager().HammerContext())
92+
needsInstall := install.PreInstallInit(graceful.GetManager().HammerContext())
9293
if needsInstall {
9394
// Flag for port number in case first time run conflict
9495
if ctx.IsSet("port") {
@@ -101,7 +102,7 @@ func runWeb(ctx *cli.Context) error {
101102
return err
102103
}
103104
}
104-
c := routes.InstallRoutes()
105+
c := install.InstallRoutes()
105106
err := listen(c, false)
106107
select {
107108
case <-graceful.GetManager().IsShutdown():
@@ -134,7 +135,7 @@ func runWeb(ctx *cli.Context) error {
134135
}
135136

136137
// Set up Chi routes
137-
c := routes.NormalRoutes()
138+
c := web.NormalRoutes()
138139
err := listen(c, true)
139140
<-graceful.GetManager().Done()
140141
log.Info("PID: %d Gitea Web Finished", os.Getpid())

models/models.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ import (
1212
"fmt"
1313
"reflect"
1414
"strings"
15+
"time"
1516

17+
"code.gitea.io/gitea/models/migrations"
18+
"code.gitea.io/gitea/modules/log"
1619
"code.gitea.io/gitea/modules/setting"
1720

1821
// Needed for the MySQL driver
@@ -229,6 +232,29 @@ func NewEngine(ctx context.Context, migrateFunc func(*xorm.Engine) error) (err e
229232
return nil
230233
}
231234

235+
// InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology
236+
func InitDBEngine(ctx context.Context) (err error) {
237+
log.Info("Beginning ORM engine initialization.")
238+
for i := 0; i < setting.Database.DBConnectRetries; i++ {
239+
select {
240+
case <-ctx.Done():
241+
return fmt.Errorf("Aborted due to shutdown:\nin retry ORM engine initialization")
242+
default:
243+
}
244+
log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries)
245+
if err = NewEngine(ctx, migrations.Migrate); err == nil {
246+
break
247+
} else if i == setting.Database.DBConnectRetries-1 {
248+
return err
249+
}
250+
log.Error("ORM engine initialization attempt #%d/%d failed. Error: %v", i+1, setting.Database.DBConnectRetries, err)
251+
log.Info("Backing off for %d seconds", int64(setting.Database.DBConnectBackoff/time.Second))
252+
time.Sleep(setting.Database.DBConnectBackoff)
253+
}
254+
HasEngine = true
255+
return nil
256+
}
257+
232258
// NamesToBean return a list of beans or an error
233259
func NamesToBean(names ...string) ([]interface{}, error) {
234260
beans := []interface{}{}

routers/api/v1/repo/file.go

Lines changed: 1 addition & 1 deletion
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/web/repo"
2121
)
2222

2323
// GetRawFile get a file by path on a repository

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)