Skip to content

Commit 5f44080

Browse files
committed
Move Recovery to middlewares
1 parent 03b1616 commit 5f44080

File tree

11 files changed

+278
-184
lines changed

11 files changed

+278
-184
lines changed

modules/context/panic.go

Lines changed: 0 additions & 41 deletions
This file was deleted.

modules/middlewares/cookie.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2020 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 middlewares
6+
7+
import (
8+
"net/http"
9+
10+
"code.gitea.io/gitea/modules/setting"
11+
)
12+
13+
// NewCookie creates a cookie
14+
func NewCookie(name, value string, maxAge int) *http.Cookie {
15+
return &http.Cookie{
16+
Name: name,
17+
Value: value,
18+
HttpOnly: true,
19+
Path: setting.SessionConfig.CookiePath,
20+
Domain: setting.SessionConfig.Domain,
21+
MaxAge: maxAge,
22+
Secure: setting.SessionConfig.Secure,
23+
}
24+
}

modules/middlewares/locale.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright 2020 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 middlewares
6+
7+
import (
8+
"net/http"
9+
10+
"code.gitea.io/gitea/modules/translation"
11+
12+
"github.com/unknwon/i18n"
13+
"golang.org/x/text/language"
14+
)
15+
16+
// Locale handle locale
17+
func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
18+
hasCookie := false
19+
20+
// 1. Check URL arguments.
21+
lang := req.URL.Query().Get("lang")
22+
23+
// 2. Get language information from cookies.
24+
if len(lang) == 0 {
25+
ck, _ := req.Cookie("lang")
26+
lang = ck.Value
27+
hasCookie = true
28+
}
29+
30+
// Check again in case someone modify by purpose.
31+
if !i18n.IsExist(lang) {
32+
lang = ""
33+
hasCookie = false
34+
}
35+
36+
// 3. Get language information from 'Accept-Language'.
37+
// The first element in the list is chosen to be the default language automatically.
38+
if len(lang) == 0 {
39+
tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
40+
tag, _, _ := translation.Match(tags...)
41+
lang = tag.String()
42+
}
43+
44+
if !hasCookie {
45+
req.AddCookie(NewCookie("lang", lang, 1<<31-1))
46+
}
47+
48+
return translation.NewLocale(lang)
49+
}

modules/middlewares/recovery.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright 2020 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 middlewares
6+
7+
import (
8+
"fmt"
9+
"net/http"
10+
11+
"code.gitea.io/gitea/modules/log"
12+
"code.gitea.io/gitea/modules/setting"
13+
"code.gitea.io/gitea/modules/templates"
14+
15+
"github.com/unrolled/render"
16+
)
17+
18+
// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so.
19+
// Although similar to macaron.Recovery() the main difference is that this error will be created
20+
// with the gitea 500 page.
21+
func Recovery() func(next http.Handler) http.Handler {
22+
return func(next http.Handler) http.Handler {
23+
rnd := render.New(render.Options{
24+
Extensions: []string{".tmpl"},
25+
Directory: "templates",
26+
Funcs: templates.NewFuncMap(),
27+
Asset: templates.GetAsset,
28+
AssetNames: templates.GetAssetNames,
29+
IsDevelopment: setting.RunMode != "prod",
30+
})
31+
32+
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
33+
defer func() {
34+
if err := recover(); err != nil {
35+
combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2)))
36+
log.Error("%v", combinedErr)
37+
38+
lc := Locale(w, req)
39+
40+
var (
41+
data = templates.Vars{
42+
"Language": lc.Language(),
43+
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
44+
"i18n": lc,
45+
}
46+
)
47+
if setting.RunMode != "prod" {
48+
data["ErrMsg"] = combinedErr
49+
}
50+
err := rnd.HTML(w, 500, "status/500", templates.BaseVars().Merge(data))
51+
if err != nil {
52+
log.Error("%v", err)
53+
}
54+
}
55+
}()
56+
57+
next.ServeHTTP(w, req)
58+
})
59+
}
60+
}

modules/templates/base.go

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@
55
package templates
66

77
import (
8+
"strings"
89
"time"
910

11+
"code.gitea.io/gitea/modules/log"
1012
"code.gitea.io/gitea/modules/setting"
13+
"code.gitea.io/gitea/modules/util"
14+
"github.com/unknwon/com"
1115
)
1216

1317
// Vars represents variables to be render in golang templates
@@ -25,20 +29,51 @@ func (vars Vars) Merge(another map[string]interface{}) Vars {
2529
func BaseVars() Vars {
2630
var startTime = time.Now()
2731
return map[string]interface{}{
28-
"IsLandingPageHome": setting.LandingPageURL == setting.LandingPageHome,
29-
"IsLandingPageExplore": setting.LandingPageURL == setting.LandingPageExplore,
32+
"IsLandingPageHome": setting.LandingPageURL == setting.LandingPageHome,
33+
"IsLandingPageExplore": setting.LandingPageURL == setting.LandingPageExplore,
3034
"IsLandingPageOrganizations": setting.LandingPageURL == setting.LandingPageOrganizations,
3135

32-
"ShowRegistrationButton": setting.Service.ShowRegistrationButton,
36+
"ShowRegistrationButton": setting.Service.ShowRegistrationButton,
3337
"ShowMilestonesDashboardPage": setting.Service.ShowMilestonesDashboardPage,
34-
"ShowFooterBranding": setting.ShowFooterBranding,
35-
"ShowFooterVersion": setting.ShowFooterVersion,
38+
"ShowFooterBranding": setting.ShowFooterBranding,
39+
"ShowFooterVersion": setting.ShowFooterVersion,
3640

37-
"EnableSwagger": setting.API.EnableSwagger,
41+
"EnableSwagger": setting.API.EnableSwagger,
3842
"EnableOpenIDSignIn": setting.Service.EnableOpenIDSignIn,
39-
"PageStartTime": startTime,
43+
"PageStartTime": startTime,
4044
"TmplLoadTimes": func() string {
4145
return time.Since(startTime).String()
4246
},
4347
}
44-
}
48+
}
49+
50+
func getDirAssetNames(dir string) []string {
51+
var tmpls []string
52+
isDir, err := util.IsDir(dir)
53+
if err != nil {
54+
log.Warn("Unable to check if templates dir %s is a directory. Error: %v", dir, err)
55+
return tmpls
56+
}
57+
if !isDir {
58+
log.Warn("Templates dir %s is a not directory.", dir)
59+
return tmpls
60+
}
61+
62+
files, err := com.StatDir(dir)
63+
if err != nil {
64+
log.Warn("Failed to read %s templates dir. %v", dir, err)
65+
return tmpls
66+
}
67+
for _, filePath := range files {
68+
if strings.HasPrefix(filePath, "mail/") {
69+
continue
70+
}
71+
72+
if !strings.HasSuffix(filePath, ".tmpl") {
73+
continue
74+
}
75+
76+
tmpls = append(tmpls, "templates/"+filePath)
77+
}
78+
return tmpls
79+
}

modules/templates/dynamic.go

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
package templates
88

99
import (
10-
"fmt"
1110
"html/template"
1211
"io/ioutil"
1312
"os"
@@ -29,8 +28,6 @@ var (
2928
)
3029

3130
func GetAsset(name string) ([]byte, error) {
32-
fmt.Println("=====2", name)
33-
3431
bs, err := ioutil.ReadFile(filepath.Join(setting.CustomPath, name))
3532
if err != nil && !os.IsNotExist(err) {
3633
return nil, err
@@ -47,39 +44,6 @@ func GetAssetNames() []string {
4744
return append(tmpls, tmpls2...)
4845
}
4946

50-
func getDirAssetNames(dir string) []string {
51-
var tmpls []string
52-
isDir, err := util.IsDir(dir)
53-
if err != nil {
54-
log.Warn("Unable to check if templates dir %s is a directory. Error: %v", dir, err)
55-
return tmpls
56-
}
57-
if !isDir {
58-
log.Warn("Templates dir %s is a not directory.", dir)
59-
return tmpls
60-
}
61-
62-
files, err := com.StatDir(dir)
63-
if err != nil {
64-
log.Warn("Failed to read %s templates dir. %v", dir, err)
65-
return tmpls
66-
}
67-
for _, filePath := range files {
68-
if strings.HasPrefix(filePath, "mail/") {
69-
continue
70-
}
71-
72-
if !strings.HasSuffix(filePath, ".tmpl") {
73-
continue
74-
}
75-
76-
fmt.Println("=======3333", filePath, filePath)
77-
78-
tmpls = append(tmpls, "templates/"+filePath)
79-
}
80-
return tmpls
81-
}
82-
8347
// HTMLRenderer implements the macaron handler for serving HTML templates.
8448
func HTMLRenderer() macaron.Handler {
8549
return macaron.Renderer(macaron.RenderOptions{

modules/templates/static.go

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import (
1212
"html/template"
1313
"io"
1414
"io/ioutil"
15+
"os"
1516
"path"
17+
"path/filepath"
1618
"strings"
1719
texttmpl "text/template"
1820

@@ -59,30 +61,10 @@ func GetAsset(name string) ([]byte, error) {
5961

6062
func GetAssetNames() []string {
6163
var tmpls = AssetNames()
62-
customDir := path.Join(setting.CustomPath, "templates")
63-
isDir, err := util.IsDir(customDir)
64-
if err != nil {
65-
log.Warn("Unable to check if templates dir %s is a directory. Error: %v", customDir, err)
66-
return tmpls
67-
}
6864

69-
files, err := com.StatDir(customDir)
70-
if err != nil {
71-
log.Warn("Failed to read %s templates dir. %v", customDir, err)
72-
return tmpls
73-
}
74-
for _, filePath := range files {
75-
if strings.HasPrefix(filePath, "mail/") {
76-
continue
77-
}
78-
79-
if !strings.HasSuffix(filePath, ".tmpl") {
80-
continue
81-
}
82-
83-
tmpls = append(tmpls, filePath)
84-
}
85-
return tmpls
65+
customDir := path.Join(setting.CustomPath, "templates")
66+
customTmpls := getDirAssetNames(customDir)
67+
return append(tmpls, customTmpls...)
8668
}
8769

8870
func NewTemplateFileSystem() templateFileSystem {

0 commit comments

Comments
 (0)