1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-03 09:07:19 +00:00

Refactor names (#31405)

This PR only does "renaming":

* `Route` should be `Router` (and chi router is also called "router")
* `Params` should be `PathParam` (to distingush it from URL query param, and to match `FormString`)
* Use lower case for private functions to avoid exposing or abusing
This commit is contained in:
wxiaoguang
2024-06-19 06:32:45 +08:00
committed by GitHub
parent 17baf1af10
commit 43c7a2e7b1
177 changed files with 837 additions and 837 deletions

View File

@ -36,16 +36,16 @@ func NewFuncMap() template.FuncMap {
// -----------------------------------------------------------------
// html/template related functions
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
"Iif": Iif,
"Eval": Eval,
"SafeHTML": SafeHTML,
"Iif": iif,
"Eval": evalTokens,
"SafeHTML": safeHTML,
"HTMLFormat": HTMLFormat,
"HTMLEscape": HTMLEscape,
"QueryEscape": QueryEscape,
"JSEscape": JSEscapeSafe,
"HTMLEscape": htmlEscape,
"QueryEscape": queryEscape,
"JSEscape": jsEscapeSafe,
"SanitizeHTML": SanitizeHTML,
"URLJoin": util.URLJoin,
"DotEscape": DotEscape,
"DotEscape": dotEscape,
"PathEscape": url.PathEscape,
"PathEscapeSegments": util.PathEscapeSegments,
@ -59,9 +59,9 @@ func NewFuncMap() template.FuncMap {
// svg / avatar / icon / color
"svg": svg.RenderHTML,
"EntryIcon": base.EntryIcon,
"MigrationIcon": MigrationIcon,
"ActionIcon": ActionIcon,
"SortArrow": SortArrow,
"MigrationIcon": migrationIcon,
"ActionIcon": actionIcon,
"SortArrow": sortArrow,
"ContrastColor": util.ContrastColor,
// -----------------------------------------------------------------
@ -139,7 +139,7 @@ func NewFuncMap() template.FuncMap {
"DisableImportLocal": func() bool {
return !setting.ImportLocalPaths
},
"UserThemeName": UserThemeName,
"UserThemeName": userThemeName,
"NotificationSettings": func() map[string]any {
return map[string]any{
"MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
@ -155,28 +155,28 @@ func NewFuncMap() template.FuncMap {
// -----------------------------------------------------------------
// render
"RenderCommitMessage": RenderCommitMessage,
"RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
"RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject,
"RenderCommitBody": RenderCommitBody,
"RenderCodeBlock": RenderCodeBlock,
"RenderIssueTitle": RenderIssueTitle,
"RenderEmoji": RenderEmoji,
"ReactionToEmoji": ReactionToEmoji,
"RenderCommitBody": renderCommitBody,
"RenderCodeBlock": renderCodeBlock,
"RenderIssueTitle": renderIssueTitle,
"RenderEmoji": renderEmoji,
"ReactionToEmoji": reactionToEmoji,
"RenderMarkdownToHtml": RenderMarkdownToHtml,
"RenderLabel": RenderLabel,
"RenderLabel": renderLabel,
"RenderLabels": RenderLabels,
// -----------------------------------------------------------------
// misc
"ShortSha": base.ShortSha,
"ActionContent2Commits": ActionContent2Commits,
"IsMultilineCommitMessage": IsMultilineCommitMessage,
"IsMultilineCommitMessage": isMultilineCommitMessage,
"CommentMustAsDiff": gitdiff.CommentMustAsDiff,
"MirrorRemoteAddress": mirrorRemoteAddress,
"FilenameIsImage": FilenameIsImage,
"TabSizeClass": TabSizeClass,
"FilenameIsImage": filenameIsImage,
"TabSizeClass": tabSizeClass,
}
}
@ -197,8 +197,8 @@ func HTMLFormat(s string, rawArgs ...any) template.HTML {
return template.HTML(fmt.Sprintf(s, args...))
}
// SafeHTML render raw as HTML
func SafeHTML(s any) template.HTML {
// safeHTML render raw as HTML
func safeHTML(s any) template.HTML {
switch v := s.(type) {
case string:
return template.HTML(v)
@ -213,7 +213,7 @@ func SanitizeHTML(s string) template.HTML {
return template.HTML(markup.Sanitize(s))
}
func HTMLEscape(s any) template.HTML {
func htmlEscape(s any) template.HTML {
switch v := s.(type) {
case string:
return template.HTML(html.EscapeString(v))
@ -223,22 +223,22 @@ func HTMLEscape(s any) template.HTML {
panic(fmt.Sprintf("unexpected type %T", s))
}
func JSEscapeSafe(s string) template.HTML {
func jsEscapeSafe(s string) template.HTML {
return template.HTML(template.JSEscapeString(s))
}
func QueryEscape(s string) template.URL {
func queryEscape(s string) template.URL {
return template.URL(url.QueryEscape(s))
}
// DotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent autolinkers from detecting these as urls
func DotEscape(raw string) string {
// dotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent auto-linkers from detecting these as urls
func dotEscape(raw string) string {
return strings.ReplaceAll(raw, ".", "\u200d.\u200d")
}
// Iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
// and it could be simply used as "{{Iif expr trueVal}}" (omit the falseVal).
func Iif(condition any, vals ...any) any {
// iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
// and it could be simply used as "{{iif expr trueVal}}" (omit the falseVal).
func iif(condition any, vals ...any) any {
if isTemplateTruthy(condition) {
return vals[0]
} else if len(vals) > 1 {
@ -273,19 +273,19 @@ func isTemplateTruthy(v any) bool {
}
}
// Eval the expression and return the result, see the comment of eval.Expr for details.
// evalTokens evaluates the expression by tokens and returns the result, see the comment of eval.Expr for details.
// To use this helper function in templates, pass each token as a separate parameter.
//
// {{ $int64 := Eval $var "+" 1 }}
// {{ $float64 := Eval $var "+" 1.0 }}
//
// Golang's template supports comparable int types, so the int64 result can be used in later statements like {{if lt $int64 10}}
func Eval(tokens ...any) (any, error) {
func evalTokens(tokens ...any) (any, error) {
n, err := eval.Expr(tokens...)
return n.Value, err
}
func UserThemeName(user *user_model.User) string {
func userThemeName(user *user_model.User) string {
if user == nil || user.Theme == "" {
return setting.UI.DefaultTheme
}

View File

@ -58,7 +58,7 @@ func TestSubjectBodySeparator(t *testing.T) {
}
func TestJSEscapeSafe(t *testing.T) {
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, JSEscapeSafe(`&<>'"`))
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, jsEscapeSafe(`&<>'"`))
}
func TestHTMLFormat(t *testing.T) {
@ -71,7 +71,7 @@ func TestSanitizeHTML(t *testing.T) {
func TestTemplateTruthy(t *testing.T) {
tmpl := template.New("test")
tmpl.Funcs(template.FuncMap{"Iif": Iif})
tmpl.Funcs(template.FuncMap{"Iif": iif})
template.Must(tmpl.Parse(`{{if .Value}}true{{else}}false{{end}}:{{Iif .Value "true" "false"}}`))
cases := []any{

View File

@ -22,7 +22,7 @@ var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}\s*$`)
func mailSubjectTextFuncMap() texttmpl.FuncMap {
return texttmpl.FuncMap{
"dict": dict,
"Eval": Eval,
"Eval": evalTokens,
"EllipsisString": base.EllipsisString,
"AppName": func() string {

View File

@ -24,7 +24,7 @@ import (
"github.com/editorconfig/editorconfig-core-go/v2"
)
func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
func sortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
// if needed
if len(normSort) == 0 || len(urlSort) == 0 {
return ""
@ -50,8 +50,8 @@ func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML
return ""
}
// IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
func IsMultilineCommitMessage(msg string) bool {
// isMultilineCommitMessage checks to see if a commit message contains multiple lines.
func isMultilineCommitMessage(msg string) bool {
return strings.Count(strings.TrimSpace(msg), "\n") >= 1
}
@ -69,8 +69,8 @@ type Actioner interface {
GetIssueInfos() []string
}
// ActionIcon accepts an action operation type and returns an icon class name.
func ActionIcon(opType activities_model.ActionType) string {
// actionIcon accepts an action operation type and returns an icon class name.
func actionIcon(opType activities_model.ActionType) string {
switch opType {
case activities_model.ActionCreateRepo, activities_model.ActionTransferRepo, activities_model.ActionRenameRepo:
return "repo"
@ -126,8 +126,8 @@ func ActionContent2Commits(act Actioner) *repository.PushCommits {
return push
}
// MigrationIcon returns a SVG name matching the service an issue/comment was migrated from
func MigrationIcon(hostname string) string {
// migrationIcon returns a SVG name matching the service an issue/comment was migrated from
func migrationIcon(hostname string) string {
switch hostname {
case "github.com":
return "octicon-mark-github"
@ -177,12 +177,12 @@ func mirrorRemoteAddress(ctx context.Context, m *repo_model.Repository, remoteNa
return ret
}
func FilenameIsImage(filename string) bool {
func filenameIsImage(filename string) bool {
mimeType := mime.TypeByExtension(filepath.Ext(filename))
return strings.HasPrefix(mimeType, "image/")
}
func TabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
func tabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
if ec != nil {
def, err := ec.GetDefinitionForFilename(filename)
if err == nil && def.TabWidth >= 1 && def.TabWidth <= 16 {

View File

@ -41,12 +41,12 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin
if len(msgLines) == 0 {
return template.HTML("")
}
return RenderCodeBlock(template.HTML(msgLines[0]))
return renderCodeBlock(template.HTML(msgLines[0]))
}
// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// the provided default url, handling for special links without email to links.
func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
@ -68,11 +68,11 @@ func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
log.Error("RenderCommitMessageSubject: %v", err)
return template.HTML("")
}
return RenderCodeBlock(template.HTML(renderedMessage))
return renderCodeBlock(template.HTML(renderedMessage))
}
// RenderCommitBody extracts the body of a commit message without its title.
func RenderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
// renderCommitBody extracts the body of a commit message without its title.
func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
msgLine := strings.TrimSpace(msg)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
@ -99,14 +99,14 @@ func RenderCommitBody(ctx context.Context, msg string, metas map[string]string)
// Match text that is between back ticks.
var codeMatcher = regexp.MustCompile("`([^`]+)`")
// RenderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
func RenderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
// renderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags
return template.HTML(htmlWithCodeTags)
}
// RenderIssueTitle renders issue/pull title with defined post processors
func RenderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
// renderIssueTitle renders issue/pull title with defined post processors
func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
Ctx: ctx,
Metas: metas,
@ -118,9 +118,9 @@ func RenderIssueTitle(ctx context.Context, text string, metas map[string]string)
return template.HTML(renderedText)
}
// RenderLabel renders a label
// renderLabel renders a label
// locale is needed due to an import cycle with our context providing the `Tr` function
func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
var extraCSSClasses string
textColor := util.ContrastColor(label.Color)
labelScope := label.ExclusiveScope()
@ -134,12 +134,12 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
if labelScope == "" {
// Regular label
return HTMLFormat(`<div class="ui label %s" style="color: %s !important; background-color: %s !important;" data-tooltip-content title="%s">%s</div>`,
extraCSSClasses, textColor, label.Color, descriptionText, RenderEmoji(ctx, label.Name))
extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name))
}
// Scoped label
scopeHTML := RenderEmoji(ctx, labelScope)
itemHTML := RenderEmoji(ctx, label.Name[len(labelScope)+1:])
scopeHTML := renderEmoji(ctx, labelScope)
itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])
// Make scope and item background colors slightly darker and lighter respectively.
// More contrast needed with higher luminance, empirically tweaked.
@ -176,8 +176,8 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
textColor, itemColor, itemHTML)
}
// RenderEmoji renders html text with emoji post processors
func RenderEmoji(ctx context.Context, text string) template.HTML {
// renderEmoji renders html text with emoji post processors
func renderEmoji(ctx context.Context, text string) template.HTML {
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
template.HTMLEscapeString(text))
if err != nil {
@ -187,8 +187,8 @@ func RenderEmoji(ctx context.Context, text string) template.HTML {
return template.HTML(renderedText)
}
// ReactionToEmoji renders emoji for use in reactions
func ReactionToEmoji(reaction string) template.HTML {
// reactionToEmoji renders emoji for use in reactions
func reactionToEmoji(reaction string) template.HTML {
val := emoji.FromCode(reaction)
if val != nil {
return template.HTML(val.Emoji)
@ -220,7 +220,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
if label == nil {
continue
}
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, RenderLabel(ctx, locale, label))
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, renderLabel(ctx, locale, label))
}
htmlCode += "</span>"
return template.HTML(htmlCode)

View File

@ -103,7 +103,7 @@ func TestRenderCommitBody(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, RenderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
assert.Equalf(t, tt.want, renderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
})
}
@ -127,7 +127,7 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit
<a href="/user13/repo11/issues/123" class="ref-issue">#123</a>
space`
assert.EqualValues(t, expected, RenderCommitBody(context.Background(), testInput(), testMetas))
assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas))
}
func TestRenderCommitMessage(t *testing.T) {
@ -139,7 +139,7 @@ func TestRenderCommitMessage(t *testing.T) {
func TestRenderCommitMessageLinkSubject(t *testing.T) {
expected := `<a href="https://example.com/link" class="default-link muted">space </a><a href="/mention-user" class="mention">@mention-user</a>`
assert.EqualValues(t, expected, RenderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
assert.EqualValues(t, expected, renderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
}
func TestRenderIssueTitle(t *testing.T) {
@ -165,7 +165,7 @@ mail@domain.com
space<SPACE><SPACE>
`
expected = strings.ReplaceAll(expected, "<SPACE>", " ")
assert.EqualValues(t, expected, RenderIssueTitle(context.Background(), testInput(), testMetas))
assert.EqualValues(t, expected, renderIssueTitle(context.Background(), testInput(), testMetas))
}
func TestRenderMarkdownToHtml(t *testing.T) {

View File

@ -36,30 +36,30 @@ func GetForm(dataStore middleware.ContextDataStore) any {
return dataStore.GetData()["__form"]
}
// Route defines a route based on chi's router
type Route struct {
R chi.Router
// Router defines a route based on chi's router
type Router struct {
chiRouter chi.Router
curGroupPrefix string
curMiddlewares []any
}
// NewRoute creates a new route
func NewRoute() *Route {
// NewRouter creates a new route
func NewRouter() *Router {
r := chi.NewRouter()
return &Route{R: r}
return &Router{chiRouter: r}
}
// Use supports two middlewares
func (r *Route) Use(middlewares ...any) {
func (r *Router) Use(middlewares ...any) {
for _, m := range middlewares {
if m != nil {
r.R.Use(toHandlerProvider(m))
r.chiRouter.Use(toHandlerProvider(m))
}
}
}
// Group mounts a sub-Router along a `pattern` string.
func (r *Route) Group(pattern string, fn func(), middlewares ...any) {
func (r *Router) Group(pattern string, fn func(), middlewares ...any) {
previousGroupPrefix := r.curGroupPrefix
previousMiddlewares := r.curMiddlewares
r.curGroupPrefix += pattern
@ -71,7 +71,7 @@ func (r *Route) Group(pattern string, fn func(), middlewares ...any) {
r.curMiddlewares = previousMiddlewares
}
func (r *Route) getPattern(pattern string) string {
func (r *Router) getPattern(pattern string) string {
newPattern := r.curGroupPrefix + pattern
if !strings.HasPrefix(newPattern, "/") {
newPattern = "/" + newPattern
@ -82,7 +82,7 @@ func (r *Route) getPattern(pattern string) string {
return strings.TrimSuffix(newPattern, "/")
}
func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Handler, http.HandlerFunc) {
func (r *Router) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Handler, http.HandlerFunc) {
handlerProviders := make([]func(http.Handler) http.Handler, 0, len(r.curMiddlewares)+len(h)+1)
for _, m := range r.curMiddlewares {
if m != nil {
@ -96,7 +96,7 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han
}
middlewares := handlerProviders[:len(handlerProviders)-1]
handlerFunc := handlerProviders[len(handlerProviders)-1](nil).ServeHTTP
mockPoint := RouteMockPoint(MockAfterMiddlewares)
mockPoint := RouterMockPoint(MockAfterMiddlewares)
if mockPoint != nil {
middlewares = append(middlewares, mockPoint)
}
@ -105,72 +105,72 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han
// Methods adds the same handlers for multiple http "methods" (separated by ",").
// If any method is invalid, the lower level router will panic.
func (r *Route) Methods(methods, pattern string, h ...any) {
func (r *Router) Methods(methods, pattern string, h ...any) {
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
fullPattern := r.getPattern(pattern)
if strings.Contains(methods, ",") {
methods := strings.Split(methods, ",")
for _, method := range methods {
r.R.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
r.chiRouter.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
}
} else {
r.R.With(middlewares...).Method(methods, fullPattern, handlerFunc)
r.chiRouter.With(middlewares...).Method(methods, fullPattern, handlerFunc)
}
}
// Mount attaches another Route along ./pattern/*
func (r *Route) Mount(pattern string, subR *Route) {
subR.Use(r.curMiddlewares...)
r.R.Mount(r.getPattern(pattern), subR.R)
// Mount attaches another Router along ./pattern/*
func (r *Router) Mount(pattern string, subRouter *Router) {
subRouter.Use(r.curMiddlewares...)
r.chiRouter.Mount(r.getPattern(pattern), subRouter.chiRouter)
}
// Any delegate requests for all methods
func (r *Route) Any(pattern string, h ...any) {
func (r *Router) Any(pattern string, h ...any) {
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
r.R.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc)
r.chiRouter.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc)
}
// Delete delegate delete method
func (r *Route) Delete(pattern string, h ...any) {
func (r *Router) Delete(pattern string, h ...any) {
r.Methods("DELETE", pattern, h...)
}
// Get delegate get method
func (r *Route) Get(pattern string, h ...any) {
func (r *Router) Get(pattern string, h ...any) {
r.Methods("GET", pattern, h...)
}
// Head delegate head method
func (r *Route) Head(pattern string, h ...any) {
func (r *Router) Head(pattern string, h ...any) {
r.Methods("HEAD", pattern, h...)
}
// Post delegate post method
func (r *Route) Post(pattern string, h ...any) {
func (r *Router) Post(pattern string, h ...any) {
r.Methods("POST", pattern, h...)
}
// Put delegate put method
func (r *Route) Put(pattern string, h ...any) {
func (r *Router) Put(pattern string, h ...any) {
r.Methods("PUT", pattern, h...)
}
// Patch delegate patch method
func (r *Route) Patch(pattern string, h ...any) {
func (r *Router) Patch(pattern string, h ...any) {
r.Methods("PATCH", pattern, h...)
}
// ServeHTTP implements http.Handler
func (r *Route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.normalizeRequestPath(w, req, r.R)
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.normalizeRequestPath(w, req, r.chiRouter)
}
// NotFound defines a handler to respond whenever a route could not be found.
func (r *Route) NotFound(h http.HandlerFunc) {
r.R.NotFound(h)
func (r *Router) NotFound(h http.HandlerFunc) {
r.chiRouter.NotFound(h)
}
func (r *Route) normalizeRequestPath(resp http.ResponseWriter, req *http.Request, next http.Handler) {
func (r *Router) normalizeRequestPath(resp http.ResponseWriter, req *http.Request, next http.Handler) {
normalized := false
normalizedPath := req.URL.EscapedPath()
if normalizedPath == "" {
@ -226,13 +226,13 @@ func (r *Route) normalizeRequestPath(resp http.ResponseWriter, req *http.Request
}
// Combo delegates requests to Combo
func (r *Route) Combo(pattern string, h ...any) *Combo {
func (r *Router) Combo(pattern string, h ...any) *Combo {
return &Combo{r, pattern, h}
}
// Combo represents a tiny group routes with same pattern
type Combo struct {
r *Route
r *Router
pattern string
h []any
}

View File

@ -22,7 +22,7 @@ func TestRoute1(t *testing.T) {
recorder := httptest.NewRecorder()
recorder.Body = buff
r := NewRoute()
r := NewRouter()
r.Get("/{username}/{reponame}/{type:issues|pulls}", func(resp http.ResponseWriter, req *http.Request) {
username := chi.URLParam(req, "username")
assert.EqualValues(t, "gitea", username)
@ -45,7 +45,7 @@ func TestRoute2(t *testing.T) {
hit := -1
r := NewRoute()
r := NewRouter()
r.Group("/{username}/{reponame}", func() {
r.Group("", func() {
r.Get("/{type:issues|pulls}", func(resp http.ResponseWriter, req *http.Request) {
@ -121,8 +121,8 @@ func TestRoute3(t *testing.T) {
hit := -1
m := NewRoute()
r := NewRoute()
m := NewRouter()
r := NewRouter()
r.Mount("/api/v1", m)
m.Group("/repos", func() {
@ -189,7 +189,7 @@ func TestRouteNormalizePath(t *testing.T) {
recorder.Body = bytes.NewBuffer(nil)
actualPaths := paths{EscapedPath: "(none)", RawPath: "(none)", Path: "(none)"}
r := NewRoute()
r := NewRouter()
r.Get("/*", func(resp http.ResponseWriter, req *http.Request) {
actualPaths.EscapedPath = req.URL.EscapedPath()
actualPaths.RawPath = req.URL.RawPath

View File

@ -14,14 +14,14 @@ const MockAfterMiddlewares = "MockAfterMiddlewares"
var routeMockPoints = map[string]func(next http.Handler) http.Handler{}
// RouteMockPoint registers a mock point as a middleware for testing, example:
// RouterMockPoint registers a mock point as a middleware for testing, example:
//
// r.Use(web.RouteMockPoint("my-mock-point-1"))
// r.Get("/foo", middleware2, web.RouteMockPoint("my-mock-point-2"), middleware2, handler)
// r.Use(web.RouterMockPoint("my-mock-point-1"))
// r.Get("/foo", middleware2, web.RouterMockPoint("my-mock-point-2"), middleware2, handler)
//
// Then use web.RouteMock to mock the route execution.
// It only takes effect in testing mode (setting.IsInTesting == true).
func RouteMockPoint(pointName string) func(next http.Handler) http.Handler {
func RouterMockPoint(pointName string) func(next http.Handler) http.Handler {
if !setting.IsInTesting {
return nil
}

View File

@ -16,7 +16,7 @@ import (
func TestRouteMock(t *testing.T) {
setting.IsInTesting = true
r := NewRoute()
r := NewRouter()
middleware1 := func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("X-Test-Middleware1", "m1")
}
@ -26,7 +26,7 @@ func TestRouteMock(t *testing.T) {
handler := func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("X-Test-Handler", "h")
}
r.Get("/foo", middleware1, RouteMockPoint("mock-point"), middleware2, handler)
r.Get("/foo", middleware1, RouterMockPoint("mock-point"), middleware2, handler)
// normal request
recorder := httptest.NewRecorder()