1
1
mirror of https://github.com/go-gitea/gitea synced 2024-12-22 16:44:26 +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
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
177 changed files with 837 additions and 837 deletions

View File

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

View File

@ -58,7 +58,7 @@ func TestSubjectBodySeparator(t *testing.T) {
} }
func TestJSEscapeSafe(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) { func TestHTMLFormat(t *testing.T) {
@ -71,7 +71,7 @@ func TestSanitizeHTML(t *testing.T) {
func TestTemplateTruthy(t *testing.T) { func TestTemplateTruthy(t *testing.T) {
tmpl := template.New("test") 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"}}`)) template.Must(tmpl.Parse(`{{if .Value}}true{{else}}false{{end}}:{{Iif .Value "true" "false"}}`))
cases := []any{ cases := []any{

View File

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

View File

@ -24,7 +24,7 @@ import (
"github.com/editorconfig/editorconfig-core-go/v2" "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 needed
if len(normSort) == 0 || len(urlSort) == 0 { if len(normSort) == 0 || len(urlSort) == 0 {
return "" return ""
@ -50,8 +50,8 @@ func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML
return "" return ""
} }
// IsMultilineCommitMessage checks to see if a commit message contains multiple lines. // isMultilineCommitMessage checks to see if a commit message contains multiple lines.
func IsMultilineCommitMessage(msg string) bool { func isMultilineCommitMessage(msg string) bool {
return strings.Count(strings.TrimSpace(msg), "\n") >= 1 return strings.Count(strings.TrimSpace(msg), "\n") >= 1
} }
@ -69,8 +69,8 @@ type Actioner interface {
GetIssueInfos() []string GetIssueInfos() []string
} }
// ActionIcon accepts an action operation type and returns an icon class name. // actionIcon accepts an action operation type and returns an icon class name.
func ActionIcon(opType activities_model.ActionType) string { func actionIcon(opType activities_model.ActionType) string {
switch opType { switch opType {
case activities_model.ActionCreateRepo, activities_model.ActionTransferRepo, activities_model.ActionRenameRepo: case activities_model.ActionCreateRepo, activities_model.ActionTransferRepo, activities_model.ActionRenameRepo:
return "repo" return "repo"
@ -126,8 +126,8 @@ func ActionContent2Commits(act Actioner) *repository.PushCommits {
return push return push
} }
// MigrationIcon returns a SVG name matching the service an issue/comment was migrated from // migrationIcon returns a SVG name matching the service an issue/comment was migrated from
func MigrationIcon(hostname string) string { func migrationIcon(hostname string) string {
switch hostname { switch hostname {
case "github.com": case "github.com":
return "octicon-mark-github" return "octicon-mark-github"
@ -177,12 +177,12 @@ func mirrorRemoteAddress(ctx context.Context, m *repo_model.Repository, remoteNa
return ret return ret
} }
func FilenameIsImage(filename string) bool { func filenameIsImage(filename string) bool {
mimeType := mime.TypeByExtension(filepath.Ext(filename)) mimeType := mime.TypeByExtension(filepath.Ext(filename))
return strings.HasPrefix(mimeType, "image/") return strings.HasPrefix(mimeType, "image/")
} }
func TabSizeClass(ec *editorconfig.Editorconfig, filename string) string { func tabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
if ec != nil { if ec != nil {
def, err := ec.GetDefinitionForFilename(filename) def, err := ec.GetDefinitionForFilename(filename)
if err == nil && def.TabWidth >= 1 && def.TabWidth <= 16 { 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 { if len(msgLines) == 0 {
return template.HTML("") 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. // 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) msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
lineEnd := strings.IndexByte(msgLine, '\n') lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 { if lineEnd > 0 {
@ -68,11 +68,11 @@ func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
log.Error("RenderCommitMessageSubject: %v", err) log.Error("RenderCommitMessageSubject: %v", err)
return template.HTML("") return template.HTML("")
} }
return RenderCodeBlock(template.HTML(renderedMessage)) return renderCodeBlock(template.HTML(renderedMessage))
} }
// RenderCommitBody extracts the body of a commit message without its title. // renderCommitBody extracts the body of a commit message without its title.
func RenderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML { func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
msgLine := strings.TrimSpace(msg) msgLine := strings.TrimSpace(msg)
lineEnd := strings.IndexByte(msgLine, '\n') lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 { 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. // Match text that is between back ticks.
var codeMatcher = regexp.MustCompile("`([^`]+)`") var codeMatcher = regexp.MustCompile("`([^`]+)`")
// RenderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles // renderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
func RenderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML { func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags
return template.HTML(htmlWithCodeTags) return template.HTML(htmlWithCodeTags)
} }
// RenderIssueTitle renders issue/pull title with defined post processors // renderIssueTitle renders issue/pull title with defined post processors
func RenderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML { func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{ renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
Ctx: ctx, Ctx: ctx,
Metas: metas, Metas: metas,
@ -118,9 +118,9 @@ func RenderIssueTitle(ctx context.Context, text string, metas map[string]string)
return template.HTML(renderedText) 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 // 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 var extraCSSClasses string
textColor := util.ContrastColor(label.Color) textColor := util.ContrastColor(label.Color)
labelScope := label.ExclusiveScope() labelScope := label.ExclusiveScope()
@ -134,12 +134,12 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
if labelScope == "" { if labelScope == "" {
// Regular label // Regular label
return HTMLFormat(`<div class="ui label %s" style="color: %s !important; background-color: %s !important;" data-tooltip-content title="%s">%s</div>`, 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 // Scoped label
scopeHTML := RenderEmoji(ctx, labelScope) scopeHTML := renderEmoji(ctx, labelScope)
itemHTML := RenderEmoji(ctx, label.Name[len(labelScope)+1:]) itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])
// Make scope and item background colors slightly darker and lighter respectively. // Make scope and item background colors slightly darker and lighter respectively.
// More contrast needed with higher luminance, empirically tweaked. // 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) textColor, itemColor, itemHTML)
} }
// RenderEmoji renders html text with emoji post processors // renderEmoji renders html text with emoji post processors
func RenderEmoji(ctx context.Context, text string) template.HTML { func renderEmoji(ctx context.Context, text string) template.HTML {
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx}, renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
template.HTMLEscapeString(text)) template.HTMLEscapeString(text))
if err != nil { if err != nil {
@ -187,8 +187,8 @@ func RenderEmoji(ctx context.Context, text string) template.HTML {
return template.HTML(renderedText) return template.HTML(renderedText)
} }
// ReactionToEmoji renders emoji for use in reactions // reactionToEmoji renders emoji for use in reactions
func ReactionToEmoji(reaction string) template.HTML { func reactionToEmoji(reaction string) template.HTML {
val := emoji.FromCode(reaction) val := emoji.FromCode(reaction)
if val != nil { if val != nil {
return template.HTML(val.Emoji) return template.HTML(val.Emoji)
@ -220,7 +220,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
if label == nil { if label == nil {
continue 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>" htmlCode += "</span>"
return template.HTML(htmlCode) return template.HTML(htmlCode)

View File

@ -103,7 +103,7 @@ func TestRenderCommitBody(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { 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> <a href="/user13/repo11/issues/123" class="ref-issue">#123</a>
space` space`
assert.EqualValues(t, expected, RenderCommitBody(context.Background(), testInput(), testMetas)) assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas))
} }
func TestRenderCommitMessage(t *testing.T) { func TestRenderCommitMessage(t *testing.T) {
@ -139,7 +139,7 @@ func TestRenderCommitMessage(t *testing.T) {
func TestRenderCommitMessageLinkSubject(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>` 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) { func TestRenderIssueTitle(t *testing.T) {
@ -165,7 +165,7 @@ mail@domain.com
space<SPACE><SPACE> space<SPACE><SPACE>
` `
expected = strings.ReplaceAll(expected, "<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) { func TestRenderMarkdownToHtml(t *testing.T) {

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@ import (
func TestRouteMock(t *testing.T) { func TestRouteMock(t *testing.T) {
setting.IsInTesting = true setting.IsInTesting = true
r := NewRoute() r := NewRouter()
middleware1 := func(resp http.ResponseWriter, req *http.Request) { middleware1 := func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("X-Test-Middleware1", "m1") resp.Header().Set("X-Test-Middleware1", "m1")
} }
@ -26,7 +26,7 @@ func TestRouteMock(t *testing.T) {
handler := func(resp http.ResponseWriter, req *http.Request) { handler := func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("X-Test-Handler", "h") 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 // normal request
recorder := httptest.NewRecorder() recorder := httptest.NewRecorder()

View File

@ -11,8 +11,8 @@ import (
"code.gitea.io/gitea/routers/api/actions/runner" "code.gitea.io/gitea/routers/api/actions/runner"
) )
func Routes(prefix string) *web.Route { func Routes(prefix string) *web.Router {
m := web.NewRoute() m := web.NewRouter()
path, handler := ping.NewPingServiceHandler() path, handler := ping.NewPingServiceHandler()
m.Post(path+"*", http.StripPrefix(prefix, handler).ServeHTTP) m.Post(path+"*", http.StripPrefix(prefix, handler).ServeHTTP)

View File

@ -101,8 +101,8 @@ func init() {
}) })
} }
func ArtifactsRoutes(prefix string) *web.Route { func ArtifactsRoutes(prefix string) *web.Router {
m := web.NewRoute() m := web.NewRouter()
m.Use(ArtifactContexter()) m.Use(ArtifactContexter())
r := artifactRoutes{ r := artifactRoutes{
@ -457,7 +457,7 @@ func (ar artifactRoutes) downloadArtifact(ctx *ArtifactContext) {
return return
} }
artifactID := ctx.ParamsInt64("artifact_id") artifactID := ctx.PathParamInt64("artifact_id")
artifact, exist, err := db.GetByID[actions.ActionArtifact](ctx, artifactID) artifact, exist, err := db.GetByID[actions.ActionArtifact](ctx, artifactID)
if err != nil { if err != nil {
log.Error("Error getting artifact: %v", err) log.Error("Error getting artifact: %v", err)

View File

@ -34,7 +34,7 @@ func validateArtifactName(ctx *ArtifactContext, artifactName string) bool {
func validateRunID(ctx *ArtifactContext) (*actions.ActionTask, int64, bool) { func validateRunID(ctx *ArtifactContext) (*actions.ActionTask, int64, bool) {
task := ctx.ActionTask task := ctx.ActionTask
runID := ctx.ParamsInt64("run_id") runID := ctx.PathParamInt64("run_id")
if task.Job.RunID != runID { if task.Job.RunID != runID {
log.Error("Error runID not match") log.Error("Error runID not match")
ctx.Error(http.StatusBadRequest, "run-id does not match") ctx.Error(http.StatusBadRequest, "run-id does not match")
@ -55,7 +55,7 @@ func validateRunIDV4(ctx *ArtifactContext, rawRunID string) (*actions.ActionTask
} }
func validateArtifactHash(ctx *ArtifactContext, artifactName string) bool { func validateArtifactHash(ctx *ArtifactContext, artifactName string) bool {
paramHash := ctx.Params("artifact_hash") paramHash := ctx.PathParam("artifact_hash")
// use artifact name to create upload url // use artifact name to create upload url
artifactHash := fmt.Sprintf("%x", md5.Sum([]byte(artifactName))) artifactHash := fmt.Sprintf("%x", md5.Sum([]byte(artifactName)))
if paramHash == artifactHash { if paramHash == artifactHash {

View File

@ -129,8 +129,8 @@ func ArtifactV4Contexter() func(next http.Handler) http.Handler {
} }
} }
func ArtifactsV4Routes(prefix string) *web.Route { func ArtifactsV4Routes(prefix string) *web.Router {
m := web.NewRoute() m := web.NewRouter()
r := artifactV4Routes{ r := artifactV4Routes{
prefix: prefix, prefix: prefix,

View File

@ -73,7 +73,7 @@ func GetRepositoryFile(ctx *context.Context) {
pv, pv,
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: alpine_service.IndexArchiveFilename, Filename: alpine_service.IndexArchiveFilename,
CompositeKey: fmt.Sprintf("%s|%s|%s", ctx.Params("branch"), ctx.Params("repository"), ctx.Params("architecture")), CompositeKey: fmt.Sprintf("%s|%s|%s", ctx.PathParam("branch"), ctx.PathParam("repository"), ctx.PathParam("architecture")),
}, },
) )
if err != nil { if err != nil {
@ -89,8 +89,8 @@ func GetRepositoryFile(ctx *context.Context) {
} }
func UploadPackageFile(ctx *context.Context) { func UploadPackageFile(ctx *context.Context) {
branch := strings.TrimSpace(ctx.Params("branch")) branch := strings.TrimSpace(ctx.PathParam("branch"))
repository := strings.TrimSpace(ctx.Params("repository")) repository := strings.TrimSpace(ctx.PathParam("repository"))
if branch == "" || repository == "" { if branch == "" || repository == "" {
apiError(ctx, http.StatusBadRequest, "invalid branch or repository") apiError(ctx, http.StatusBadRequest, "invalid branch or repository")
return return
@ -182,14 +182,14 @@ func UploadPackageFile(ctx *context.Context) {
} }
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
branch := ctx.Params("branch") branch := ctx.PathParam("branch")
repository := ctx.Params("repository") repository := ctx.PathParam("repository")
architecture := ctx.Params("architecture") architecture := ctx.PathParam("architecture")
opts := &packages_model.PackageFileSearchOptions{ opts := &packages_model.PackageFileSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
PackageType: packages_model.TypeAlpine, PackageType: packages_model.TypeAlpine,
Query: ctx.Params("filename"), Query: ctx.PathParam("filename"),
CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture), CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture),
} }
pfs, _, err := packages_model.SearchFiles(ctx, opts) pfs, _, err := packages_model.SearchFiles(ctx, opts)
@ -230,12 +230,12 @@ func DownloadPackageFile(ctx *context.Context) {
} }
func DeletePackageFile(ctx *context.Context) { func DeletePackageFile(ctx *context.Context) {
branch, repository, architecture := ctx.Params("branch"), ctx.Params("repository"), ctx.Params("architecture") branch, repository, architecture := ctx.PathParam("branch"), ctx.PathParam("repository"), ctx.PathParam("architecture")
pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{ pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
PackageType: packages_model.TypeAlpine, PackageType: packages_model.TypeAlpine,
Query: ctx.Params("filename"), Query: ctx.PathParam("filename"),
CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture), CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture),
}) })
if err != nil { if err != nil {

View File

@ -74,7 +74,7 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.Context) {
} }
} }
func verifyAuth(r *web.Route, authMethods []auth.Method) { func verifyAuth(r *web.Router, authMethods []auth.Method) {
if setting.Service.EnableReverseProxyAuth { if setting.Service.EnableReverseProxyAuth {
authMethods = append(authMethods, &auth.ReverseProxy{}) authMethods = append(authMethods, &auth.ReverseProxy{})
} }
@ -94,8 +94,8 @@ func verifyAuth(r *web.Route, authMethods []auth.Method) {
// CommonRoutes provide endpoints for most package managers (except containers - see below) // CommonRoutes provide endpoints for most package managers (except containers - see below)
// These are mounted on `/api/packages` (not `/api/v1/packages`) // These are mounted on `/api/packages` (not `/api/v1/packages`)
func CommonRoutes() *web.Route { func CommonRoutes() *web.Router {
r := web.NewRoute() r := web.NewRouter()
r.Use(context.PackageContexter()) r.Use(context.PackageContexter())
@ -264,15 +264,15 @@ func CommonRoutes() *web.Route {
) )
r.Get("/*", func(ctx *context.Context) { r.Get("/*", func(ctx *context.Context) {
m := downloadPattern.FindStringSubmatch(ctx.Params("*")) m := downloadPattern.FindStringSubmatch(ctx.PathParam("*"))
if len(m) == 0 { if len(m) == 0 {
ctx.Status(http.StatusNotFound) ctx.Status(http.StatusNotFound)
return return
} }
ctx.SetParams("channel", strings.TrimSuffix(m[1], "/")) ctx.SetPathParam("channel", strings.TrimSuffix(m[1], "/"))
ctx.SetParams("architecture", m[2]) ctx.SetPathParam("architecture", m[2])
ctx.SetParams("filename", m[3]) ctx.SetPathParam("filename", m[3])
switch m[3] { switch m[3] {
case "repodata.json", "repodata.json.bz2", "current_repodata.json", "current_repodata.json.bz2": case "repodata.json", "repodata.json.bz2", "current_repodata.json", "current_repodata.json.bz2":
@ -282,14 +282,14 @@ func CommonRoutes() *web.Route {
} }
}) })
r.Put("/*", reqPackageAccess(perm.AccessModeWrite), func(ctx *context.Context) { r.Put("/*", reqPackageAccess(perm.AccessModeWrite), func(ctx *context.Context) {
m := uploadPattern.FindStringSubmatch(ctx.Params("*")) m := uploadPattern.FindStringSubmatch(ctx.PathParam("*"))
if len(m) == 0 { if len(m) == 0 {
ctx.Status(http.StatusNotFound) ctx.Status(http.StatusNotFound)
return return
} }
ctx.SetParams("channel", strings.TrimSuffix(m[1], "/")) ctx.SetPathParam("channel", strings.TrimSuffix(m[1], "/"))
ctx.SetParams("filename", m[2]) ctx.SetPathParam("filename", m[2])
conda.UploadPackageFile(ctx) conda.UploadPackageFile(ctx)
}) })
@ -339,11 +339,11 @@ func CommonRoutes() *web.Route {
// Manual mapping of routes because the package name contains slashes which chi does not support // Manual mapping of routes because the package name contains slashes which chi does not support
// https://go.dev/ref/mod#goproxy-protocol // https://go.dev/ref/mod#goproxy-protocol
r.Get("/*", func(ctx *context.Context) { r.Get("/*", func(ctx *context.Context) {
path := ctx.Params("*") path := ctx.PathParam("*")
if strings.HasSuffix(path, "/@latest") { if strings.HasSuffix(path, "/@latest") {
ctx.SetParams("name", path[:len(path)-len("/@latest")]) ctx.SetPathParam("name", path[:len(path)-len("/@latest")])
ctx.SetParams("version", "latest") ctx.SetPathParam("version", "latest")
goproxy.PackageVersionMetadata(ctx) goproxy.PackageVersionMetadata(ctx)
return return
@ -355,7 +355,7 @@ func CommonRoutes() *web.Route {
return return
} }
ctx.SetParams("name", parts[0]) ctx.SetPathParam("name", parts[0])
// <package/name>/@v/list // <package/name>/@v/list
if parts[1] == "list" { if parts[1] == "list" {
@ -365,21 +365,21 @@ func CommonRoutes() *web.Route {
// <package/name>/@v/<version>.zip // <package/name>/@v/<version>.zip
if strings.HasSuffix(parts[1], ".zip") { if strings.HasSuffix(parts[1], ".zip") {
ctx.SetParams("version", parts[1][:len(parts[1])-len(".zip")]) ctx.SetPathParam("version", parts[1][:len(parts[1])-len(".zip")])
goproxy.DownloadPackageFile(ctx) goproxy.DownloadPackageFile(ctx)
return return
} }
// <package/name>/@v/<version>.info // <package/name>/@v/<version>.info
if strings.HasSuffix(parts[1], ".info") { if strings.HasSuffix(parts[1], ".info") {
ctx.SetParams("version", parts[1][:len(parts[1])-len(".info")]) ctx.SetPathParam("version", parts[1][:len(parts[1])-len(".info")])
goproxy.PackageVersionMetadata(ctx) goproxy.PackageVersionMetadata(ctx)
return return
} }
// <package/name>/@v/<version>.mod // <package/name>/@v/<version>.mod
if strings.HasSuffix(parts[1], ".mod") { if strings.HasSuffix(parts[1], ".mod") {
ctx.SetParams("version", parts[1][:len(parts[1])-len(".mod")]) ctx.SetPathParam("version", parts[1][:len(parts[1])-len(".mod")])
goproxy.PackageVersionGoModContent(ctx) goproxy.PackageVersionGoModContent(ctx)
return return
@ -525,7 +525,7 @@ func CommonRoutes() *web.Route {
) )
r.Methods("HEAD,GET,PUT,DELETE", "*", func(ctx *context.Context) { r.Methods("HEAD,GET,PUT,DELETE", "*", func(ctx *context.Context) {
path := ctx.Params("*") path := ctx.PathParam("*")
isHead := ctx.Req.Method == "HEAD" isHead := ctx.Req.Method == "HEAD"
isGetHead := ctx.Req.Method == "HEAD" || ctx.Req.Method == "GET" isGetHead := ctx.Req.Method == "HEAD" || ctx.Req.Method == "GET"
isPut := ctx.Req.Method == "PUT" isPut := ctx.Req.Method == "PUT"
@ -533,15 +533,15 @@ func CommonRoutes() *web.Route {
m := repoPattern.FindStringSubmatch(path) m := repoPattern.FindStringSubmatch(path)
if len(m) == 2 && isGetHead { if len(m) == 2 && isGetHead {
ctx.SetParams("group", strings.Trim(m[1], "/")) ctx.SetPathParam("group", strings.Trim(m[1], "/"))
rpm.GetRepositoryConfig(ctx) rpm.GetRepositoryConfig(ctx)
return return
} }
m = repoFilePattern.FindStringSubmatch(path) m = repoFilePattern.FindStringSubmatch(path)
if len(m) == 3 && isGetHead { if len(m) == 3 && isGetHead {
ctx.SetParams("group", strings.Trim(m[1], "/")) ctx.SetPathParam("group", strings.Trim(m[1], "/"))
ctx.SetParams("filename", m[2]) ctx.SetPathParam("filename", m[2])
if isHead { if isHead {
rpm.CheckRepositoryFileExistence(ctx) rpm.CheckRepositoryFileExistence(ctx)
} else { } else {
@ -556,17 +556,17 @@ func CommonRoutes() *web.Route {
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.SetParams("group", strings.Trim(m[1], "/")) ctx.SetPathParam("group", strings.Trim(m[1], "/"))
rpm.UploadPackageFile(ctx) rpm.UploadPackageFile(ctx)
return return
} }
m = filePattern.FindStringSubmatch(path) m = filePattern.FindStringSubmatch(path)
if len(m) == 6 && (isGetHead || isDelete) { if len(m) == 6 && (isGetHead || isDelete) {
ctx.SetParams("group", strings.Trim(m[1], "/")) ctx.SetPathParam("group", strings.Trim(m[1], "/"))
ctx.SetParams("name", m[2]) ctx.SetPathParam("name", m[2])
ctx.SetParams("version", m[3]) ctx.SetPathParam("version", m[3])
ctx.SetParams("architecture", m[4]) ctx.SetPathParam("architecture", m[4])
if isGetHead { if isGetHead {
rpm.DownloadPackageFile(ctx) rpm.DownloadPackageFile(ctx)
} else { } else {
@ -607,13 +607,13 @@ func CommonRoutes() *web.Route {
r.Get("", func(ctx *context.Context) { r.Get("", func(ctx *context.Context) {
// Can't use normal routes here: https://github.com/go-chi/chi/issues/781 // Can't use normal routes here: https://github.com/go-chi/chi/issues/781
version := ctx.Params("version") version := ctx.PathParam("version")
if strings.HasSuffix(version, ".zip") { if strings.HasSuffix(version, ".zip") {
swift.CheckAcceptMediaType(swift.AcceptZip)(ctx) swift.CheckAcceptMediaType(swift.AcceptZip)(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.SetParams("version", version[:len(version)-4]) ctx.SetPathParam("version", version[:len(version)-4])
swift.DownloadPackageFile(ctx) swift.DownloadPackageFile(ctx)
} else { } else {
swift.CheckAcceptMediaType(swift.AcceptJSON)(ctx) swift.CheckAcceptMediaType(swift.AcceptJSON)(ctx)
@ -621,7 +621,7 @@ func CommonRoutes() *web.Route {
return return
} }
if strings.HasSuffix(version, ".json") { if strings.HasSuffix(version, ".json") {
ctx.SetParams("version", version[:len(version)-5]) ctx.SetPathParam("version", version[:len(version)-5])
} }
swift.PackageVersionMetadata(ctx) swift.PackageVersionMetadata(ctx)
} }
@ -651,8 +651,8 @@ func CommonRoutes() *web.Route {
// ContainerRoutes provides endpoints that implement the OCI API to serve containers // ContainerRoutes provides endpoints that implement the OCI API to serve containers
// These have to be mounted on `/v2/...` to comply with the OCI spec: // These have to be mounted on `/v2/...` to comply with the OCI spec:
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md // https://github.com/opencontainers/distribution-spec/blob/main/spec.md
func ContainerRoutes() *web.Route { func ContainerRoutes() *web.Router {
r := web.NewRoute() r := web.NewRouter()
r.Use(context.PackageContexter()) r.Use(context.PackageContexter())
@ -700,7 +700,7 @@ func ContainerRoutes() *web.Route {
// Manual mapping of routes because {image} can contain slashes which chi does not support // Manual mapping of routes because {image} can contain slashes which chi does not support
r.Methods("HEAD,GET,POST,PUT,PATCH,DELETE", "/*", func(ctx *context.Context) { r.Methods("HEAD,GET,POST,PUT,PATCH,DELETE", "/*", func(ctx *context.Context) {
path := ctx.Params("*") path := ctx.PathParam("*")
isHead := ctx.Req.Method == "HEAD" isHead := ctx.Req.Method == "HEAD"
isGet := ctx.Req.Method == "GET" isGet := ctx.Req.Method == "GET"
isPost := ctx.Req.Method == "POST" isPost := ctx.Req.Method == "POST"
@ -714,7 +714,7 @@ func ContainerRoutes() *web.Route {
return return
} }
ctx.SetParams("image", path[:len(path)-14]) ctx.SetPathParam("image", path[:len(path)-14])
container.VerifyImageName(ctx) container.VerifyImageName(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -724,7 +724,7 @@ func ContainerRoutes() *web.Route {
return return
} }
if isGet && strings.HasSuffix(path, "/tags/list") { if isGet && strings.HasSuffix(path, "/tags/list") {
ctx.SetParams("image", path[:len(path)-10]) ctx.SetPathParam("image", path[:len(path)-10])
container.VerifyImageName(ctx) container.VerifyImageName(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -741,13 +741,13 @@ func ContainerRoutes() *web.Route {
return return
} }
ctx.SetParams("image", m[1]) ctx.SetPathParam("image", m[1])
container.VerifyImageName(ctx) container.VerifyImageName(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.SetParams("uuid", m[2]) ctx.SetPathParam("uuid", m[2])
if isGet { if isGet {
container.GetUploadBlob(ctx) container.GetUploadBlob(ctx)
@ -762,13 +762,13 @@ func ContainerRoutes() *web.Route {
} }
m = blobsPattern.FindStringSubmatch(path) m = blobsPattern.FindStringSubmatch(path)
if len(m) == 3 && (isHead || isGet || isDelete) { if len(m) == 3 && (isHead || isGet || isDelete) {
ctx.SetParams("image", m[1]) ctx.SetPathParam("image", m[1])
container.VerifyImageName(ctx) container.VerifyImageName(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.SetParams("digest", m[2]) ctx.SetPathParam("digest", m[2])
if isHead { if isHead {
container.HeadBlob(ctx) container.HeadBlob(ctx)
@ -785,13 +785,13 @@ func ContainerRoutes() *web.Route {
} }
m = manifestsPattern.FindStringSubmatch(path) m = manifestsPattern.FindStringSubmatch(path)
if len(m) == 3 && (isHead || isGet || isPut || isDelete) { if len(m) == 3 && (isHead || isGet || isPut || isDelete) {
ctx.SetParams("image", m[1]) ctx.SetPathParam("image", m[1])
container.VerifyImageName(ctx) container.VerifyImageName(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.SetParams("reference", m[2]) ctx.SetPathParam("reference", m[2])
if isHead { if isHead {
container.HeadManifest(ctx) container.HeadManifest(ctx)

View File

@ -55,7 +55,7 @@ func RepositoryConfig(ctx *context.Context) {
} }
func EnumeratePackageVersions(ctx *context.Context) { func EnumeratePackageVersions(ctx *context.Context) {
p, err := packages_model.GetPackageByName(ctx, ctx.Package.Owner.ID, packages_model.TypeCargo, ctx.Params("package")) p, err := packages_model.GetPackageByName(ctx, ctx.Package.Owner.ID, packages_model.TypeCargo, ctx.PathParam("package"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)
@ -173,11 +173,11 @@ func DownloadPackageFile(ctx *context.Context) {
&packages_service.PackageInfo{ &packages_service.PackageInfo{
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
PackageType: packages_model.TypeCargo, PackageType: packages_model.TypeCargo,
Name: ctx.Params("package"), Name: ctx.PathParam("package"),
Version: ctx.Params("version"), Version: ctx.PathParam("version"),
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: strings.ToLower(fmt.Sprintf("%s-%s.crate", ctx.Params("package"), ctx.Params("version"))), Filename: strings.ToLower(fmt.Sprintf("%s-%s.crate", ctx.PathParam("package"), ctx.PathParam("version"))),
}, },
) )
if err != nil { if err != nil {
@ -274,7 +274,7 @@ func UnyankPackage(ctx *context.Context) {
} }
func yankPackage(ctx *context.Context, yank bool) { func yankPackage(ctx *context.Context, yank bool) {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeCargo, ctx.Params("package"), ctx.Params("version")) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeCargo, ctx.PathParam("package"), ctx.PathParam("version"))
if err != nil { if err != nil {
if err == packages_model.ErrPackageNotExist { if err == packages_model.ErrPackageNotExist {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)

View File

@ -150,7 +150,7 @@ func EnumeratePackages(ctx *context.Context) {
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_show.rb // https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_show.rb
func PackageMetadata(ctx *context.Context) { func PackageMetadata(ctx *context.Context) {
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, packageName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, packageName)
if err != nil { if err != nil {
@ -211,8 +211,8 @@ func PackageMetadata(ctx *context.Context) {
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_show.rb // https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_show.rb
func PackageVersionMetadata(ctx *context.Context) { func PackageVersionMetadata(ctx *context.Context) {
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
packageVersion := strings.ReplaceAll(ctx.Params("version"), "_", ".") // Chef calls this endpoint with "_" instead of "."?! packageVersion := strings.ReplaceAll(ctx.PathParam("version"), "_", ".") // Chef calls this endpoint with "_" instead of "."?!
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, packageName, packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, packageName, packageVersion)
if err != nil { if err != nil {
@ -325,7 +325,7 @@ func UploadPackage(ctx *context.Context) {
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_download.rb // https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_download.rb
func DownloadPackage(ctx *context.Context) { func DownloadPackage(ctx *context.Context) {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, ctx.Params("name"), ctx.Params("version")) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, ctx.PathParam("name"), ctx.PathParam("version"))
if err != nil { if err != nil {
if err == packages_model.ErrPackageNotExist { if err == packages_model.ErrPackageNotExist {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)
@ -354,8 +354,8 @@ func DownloadPackage(ctx *context.Context) {
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_unshare.rb // https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_unshare.rb
func DeletePackageVersion(ctx *context.Context) { func DeletePackageVersion(ctx *context.Context) {
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
err := packages_service.RemovePackageVersionByNameAndVersion( err := packages_service.RemovePackageVersionByNameAndVersion(
ctx, ctx,
@ -381,7 +381,7 @@ func DeletePackageVersion(ctx *context.Context) {
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_unshare.rb // https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_unshare.rb
func DeletePackage(ctx *context.Context) { func DeletePackage(ctx *context.Context) {
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, ctx.Params("name")) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeChef, ctx.PathParam("name"))
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return

View File

@ -134,8 +134,8 @@ func EnumeratePackages(ctx *context.Context) {
// PackageMetadata returns the metadata for a single package // PackageMetadata returns the metadata for a single package
// https://packagist.org/apidoc#get-package-data // https://packagist.org/apidoc#get-package-data
func PackageMetadata(ctx *context.Context) { func PackageMetadata(ctx *context.Context) {
vendorName := ctx.Params("vendorname") vendorName := ctx.PathParam("vendorname")
projectName := ctx.Params("projectname") projectName := ctx.PathParam("projectname")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeComposer, vendorName+"/"+projectName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeComposer, vendorName+"/"+projectName)
if err != nil { if err != nil {
@ -168,11 +168,11 @@ func DownloadPackageFile(ctx *context.Context) {
&packages_service.PackageInfo{ &packages_service.PackageInfo{
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
PackageType: packages_model.TypeComposer, PackageType: packages_model.TypeComposer,
Name: ctx.Params("package"), Name: ctx.PathParam("package"),
Version: ctx.Params("version"), Version: ctx.PathParam("version"),
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
}, },
) )
if err != nil { if err != nil {

View File

@ -72,11 +72,11 @@ func baseURL(ctx *context.Context) string {
// ExtractPathParameters is a middleware to extract common parameters from path // ExtractPathParameters is a middleware to extract common parameters from path
func ExtractPathParameters(ctx *context.Context) { func ExtractPathParameters(ctx *context.Context) {
rref, err := conan_module.NewRecipeReference( rref, err := conan_module.NewRecipeReference(
ctx.Params("name"), ctx.PathParam("name"),
ctx.Params("version"), ctx.PathParam("version"),
ctx.Params("user"), ctx.PathParam("user"),
ctx.Params("channel"), ctx.PathParam("channel"),
ctx.Params("recipe_revision"), ctx.PathParam("recipe_revision"),
) )
if err != nil { if err != nil {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
@ -85,14 +85,14 @@ func ExtractPathParameters(ctx *context.Context) {
ctx.Data[recipeReferenceKey] = rref ctx.Data[recipeReferenceKey] = rref
reference := ctx.Params("package_reference") reference := ctx.PathParam("package_reference")
var pref *conan_module.PackageReference var pref *conan_module.PackageReference
if reference != "" { if reference != "" {
pref, err = conan_module.NewPackageReference( pref, err = conan_module.NewPackageReference(
rref, rref,
reference, reference,
ctx.Params("package_revision"), ctx.PathParam("package_revision"),
) )
if err != nil { if err != nil {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
@ -304,7 +304,7 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey
rref := ctx.Data[recipeReferenceKey].(*conan_module.RecipeReference) rref := ctx.Data[recipeReferenceKey].(*conan_module.RecipeReference)
pref := ctx.Data[packageReferenceKey].(*conan_module.PackageReference) pref := ctx.Data[packageReferenceKey].(*conan_module.PackageReference)
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
if !fileFilter.Contains(filename) { if !fileFilter.Contains(filename) {
apiError(ctx, http.StatusBadRequest, nil) apiError(ctx, http.StatusBadRequest, nil)
return return
@ -444,7 +444,7 @@ func DownloadPackageFile(ctx *context.Context) {
func downloadFile(ctx *context.Context, fileFilter container.Set[string], fileKey string) { func downloadFile(ctx *context.Context, fileFilter container.Set[string], fileKey string) {
rref := ctx.Data[recipeReferenceKey].(*conan_module.RecipeReference) rref := ctx.Data[recipeReferenceKey].(*conan_module.RecipeReference)
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
if !fileFilter.Contains(filename) { if !fileFilter.Contains(filename) {
apiError(ctx, http.StatusBadRequest, nil) apiError(ctx, http.StatusBadRequest, nil)
return return

View File

@ -66,7 +66,7 @@ func EnumeratePackages(ctx *context.Context) {
repoData := &RepoData{ repoData := &RepoData{
Info: Info{ Info: Info{
Subdir: ctx.Params("architecture"), Subdir: ctx.PathParam("architecture"),
}, },
Packages: make(map[string]*PackageInfo), Packages: make(map[string]*PackageInfo),
PackagesConda: make(map[string]*PackageInfo), PackagesConda: make(map[string]*PackageInfo),
@ -75,7 +75,7 @@ func EnumeratePackages(ctx *context.Context) {
pfs, err := conda_model.SearchFiles(ctx, &conda_model.FileSearchOptions{ pfs, err := conda_model.SearchFiles(ctx, &conda_model.FileSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
Channel: ctx.Params("channel"), Channel: ctx.PathParam("channel"),
Subdir: repoData.Info.Subdir, Subdir: repoData.Info.Subdir,
}) })
if err != nil { if err != nil {
@ -151,7 +151,7 @@ func EnumeratePackages(ctx *context.Context) {
var w io.Writer = resp var w io.Writer = resp
if strings.HasSuffix(ctx.Params("filename"), ".json") { if strings.HasSuffix(ctx.PathParam("filename"), ".json") {
resp.Header().Set("Content-Type", "application/json") resp.Header().Set("Content-Type", "application/json")
} else { } else {
resp.Header().Set("Content-Type", "application/x-bzip2") resp.Header().Set("Content-Type", "application/x-bzip2")
@ -191,7 +191,7 @@ func UploadPackageFile(ctx *context.Context) {
defer buf.Close() defer buf.Close()
var pck *conda_module.Package var pck *conda_module.Package
if strings.HasSuffix(strings.ToLower(ctx.Params("filename")), ".tar.bz2") { if strings.HasSuffix(strings.ToLower(ctx.PathParam("filename")), ".tar.bz2") {
pck, err = conda_module.ParsePackageBZ2(buf) pck, err = conda_module.ParsePackageBZ2(buf)
} else { } else {
pck, err = conda_module.ParsePackageConda(buf, buf.Size()) pck, err = conda_module.ParsePackageConda(buf, buf.Size())
@ -212,7 +212,7 @@ func UploadPackageFile(ctx *context.Context) {
fullName := pck.Name fullName := pck.Name
channel := ctx.Params("channel") channel := ctx.PathParam("channel")
if channel != "" { if channel != "" {
fullName = channel + "/" + pck.Name fullName = channel + "/" + pck.Name
} }
@ -277,9 +277,9 @@ func UploadPackageFile(ctx *context.Context) {
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
pfs, err := conda_model.SearchFiles(ctx, &conda_model.FileSearchOptions{ pfs, err := conda_model.SearchFiles(ctx, &conda_model.FileSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
Channel: ctx.Params("channel"), Channel: ctx.PathParam("channel"),
Subdir: ctx.Params("architecture"), Subdir: ctx.PathParam("architecture"),
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
}) })
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)

View File

@ -131,7 +131,7 @@ func ReqContainerAccess(ctx *context.Context) {
// VerifyImageName is a middleware which checks if the image name is allowed // VerifyImageName is a middleware which checks if the image name is allowed
func VerifyImageName(ctx *context.Context) { func VerifyImageName(ctx *context.Context) {
if !imageNamePattern.MatchString(ctx.Params("image")) { if !imageNamePattern.MatchString(ctx.PathParam("image")) {
apiErrorDefined(ctx, errNameInvalid) apiErrorDefined(ctx, errNameInvalid)
} }
} }
@ -216,7 +216,7 @@ func GetRepositoryList(ctx *context.Context) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#single-post // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#single-post
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks
func InitiateUploadBlob(ctx *context.Context) { func InitiateUploadBlob(ctx *context.Context) {
image := ctx.Params("image") image := ctx.PathParam("image")
mount := ctx.FormTrim("mount") mount := ctx.FormTrim("mount")
from := ctx.FormTrim("from") from := ctx.FormTrim("from")
@ -305,7 +305,7 @@ func InitiateUploadBlob(ctx *context.Context) {
// https://docs.docker.com/registry/spec/api/#get-blob-upload // https://docs.docker.com/registry/spec/api/#get-blob-upload
func GetUploadBlob(ctx *context.Context) { func GetUploadBlob(ctx *context.Context) {
uuid := ctx.Params("uuid") uuid := ctx.PathParam("uuid")
upload, err := packages_model.GetBlobUploadByID(ctx, uuid) upload, err := packages_model.GetBlobUploadByID(ctx, uuid)
if err != nil { if err != nil {
@ -326,9 +326,9 @@ func GetUploadBlob(ctx *context.Context) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks
func UploadBlob(ctx *context.Context) { func UploadBlob(ctx *context.Context) {
image := ctx.Params("image") image := ctx.PathParam("image")
uploader, err := container_service.NewBlobUploader(ctx, ctx.Params("uuid")) uploader, err := container_service.NewBlobUploader(ctx, ctx.PathParam("uuid"))
if err != nil { if err != nil {
if err == packages_model.ErrPackageBlobUploadNotExist { if err == packages_model.ErrPackageBlobUploadNotExist {
apiErrorDefined(ctx, errBlobUploadUnknown) apiErrorDefined(ctx, errBlobUploadUnknown)
@ -371,7 +371,7 @@ func UploadBlob(ctx *context.Context) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks
func EndUploadBlob(ctx *context.Context) { func EndUploadBlob(ctx *context.Context) {
image := ctx.Params("image") image := ctx.PathParam("image")
digest := ctx.FormTrim("digest") digest := ctx.FormTrim("digest")
if digest == "" { if digest == "" {
@ -379,7 +379,7 @@ func EndUploadBlob(ctx *context.Context) {
return return
} }
uploader, err := container_service.NewBlobUploader(ctx, ctx.Params("uuid")) uploader, err := container_service.NewBlobUploader(ctx, ctx.PathParam("uuid"))
if err != nil { if err != nil {
if err == packages_model.ErrPackageBlobUploadNotExist { if err == packages_model.ErrPackageBlobUploadNotExist {
apiErrorDefined(ctx, errBlobUploadUnknown) apiErrorDefined(ctx, errBlobUploadUnknown)
@ -446,7 +446,7 @@ func EndUploadBlob(ctx *context.Context) {
// https://docs.docker.com/registry/spec/api/#delete-blob-upload // https://docs.docker.com/registry/spec/api/#delete-blob-upload
func CancelUploadBlob(ctx *context.Context) { func CancelUploadBlob(ctx *context.Context) {
uuid := ctx.Params("uuid") uuid := ctx.PathParam("uuid")
_, err := packages_model.GetBlobUploadByID(ctx, uuid) _, err := packages_model.GetBlobUploadByID(ctx, uuid)
if err != nil { if err != nil {
@ -469,7 +469,7 @@ func CancelUploadBlob(ctx *context.Context) {
} }
func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescriptor, error) { func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescriptor, error) {
d := ctx.Params("digest") d := ctx.PathParam("digest")
if digest.Digest(d).Validate() != nil { if digest.Digest(d).Validate() != nil {
return nil, container_model.ErrContainerBlobNotExist return nil, container_model.ErrContainerBlobNotExist
@ -477,7 +477,7 @@ func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescri
return workaroundGetContainerBlob(ctx, &container_model.BlobSearchOptions{ return workaroundGetContainerBlob(ctx, &container_model.BlobSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
Image: ctx.Params("image"), Image: ctx.PathParam("image"),
Digest: d, Digest: d,
}) })
} }
@ -518,14 +518,14 @@ func GetBlob(ctx *context.Context) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#deleting-blobs // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#deleting-blobs
func DeleteBlob(ctx *context.Context) { func DeleteBlob(ctx *context.Context) {
d := ctx.Params("digest") d := ctx.PathParam("digest")
if digest.Digest(d).Validate() != nil { if digest.Digest(d).Validate() != nil {
apiErrorDefined(ctx, errBlobUnknown) apiErrorDefined(ctx, errBlobUnknown)
return return
} }
if err := deleteBlob(ctx, ctx.Package.Owner.ID, ctx.Params("image"), d); err != nil { if err := deleteBlob(ctx, ctx.Package.Owner.ID, ctx.PathParam("image"), d); err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
} }
@ -537,13 +537,13 @@ func DeleteBlob(ctx *context.Context) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests
func UploadManifest(ctx *context.Context) { func UploadManifest(ctx *context.Context) {
reference := ctx.Params("reference") reference := ctx.PathParam("reference")
mci := &manifestCreationInfo{ mci := &manifestCreationInfo{
MediaType: ctx.Req.Header.Get("Content-Type"), MediaType: ctx.Req.Header.Get("Content-Type"),
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
Creator: ctx.Doer, Creator: ctx.Doer,
Image: ctx.Params("image"), Image: ctx.PathParam("image"),
Reference: reference, Reference: reference,
IsTagged: digest.Digest(reference).Validate() != nil, IsTagged: digest.Digest(reference).Validate() != nil,
} }
@ -592,11 +592,11 @@ func UploadManifest(ctx *context.Context) {
} }
func getBlobSearchOptionsFromContext(ctx *context.Context) (*container_model.BlobSearchOptions, error) { func getBlobSearchOptionsFromContext(ctx *context.Context) (*container_model.BlobSearchOptions, error) {
reference := ctx.Params("reference") reference := ctx.PathParam("reference")
opts := &container_model.BlobSearchOptions{ opts := &container_model.BlobSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
Image: ctx.Params("image"), Image: ctx.PathParam("image"),
IsManifest: true, IsManifest: true,
} }
@ -719,7 +719,7 @@ func serveBlob(ctx *context.Context, pfd *packages_model.PackageFileDescriptor)
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#content-discovery // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#content-discovery
func GetTagList(ctx *context.Context) { func GetTagList(ctx *context.Context) {
image := ctx.Params("image") image := ctx.PathParam("image")
if _, err := packages_model.GetPackageByName(ctx, ctx.Package.Owner.ID, packages_model.TypeContainer, image); err != nil { if _, err := packages_model.GetPackageByName(ctx, ctx.Package.Owner.ID, packages_model.TypeContainer, image); err != nil {
if err == packages_model.ErrPackageNotExist { if err == packages_model.ErrPackageNotExist {

View File

@ -28,18 +28,18 @@ func apiError(ctx *context.Context, status int, obj any) {
} }
func EnumerateSourcePackages(ctx *context.Context) { func EnumerateSourcePackages(ctx *context.Context) {
enumeratePackages(ctx, ctx.Params("format"), &cran_model.SearchOptions{ enumeratePackages(ctx, ctx.PathParam("format"), &cran_model.SearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
FileType: cran_module.TypeSource, FileType: cran_module.TypeSource,
}) })
} }
func EnumerateBinaryPackages(ctx *context.Context) { func EnumerateBinaryPackages(ctx *context.Context) {
enumeratePackages(ctx, ctx.Params("format"), &cran_model.SearchOptions{ enumeratePackages(ctx, ctx.PathParam("format"), &cran_model.SearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
FileType: cran_module.TypeBinary, FileType: cran_module.TypeBinary,
Platform: ctx.Params("platform"), Platform: ctx.PathParam("platform"),
RVersion: ctx.Params("rversion"), RVersion: ctx.PathParam("rversion"),
}) })
} }
@ -225,7 +225,7 @@ func DownloadSourcePackageFile(ctx *context.Context) {
downloadPackageFile(ctx, &cran_model.SearchOptions{ downloadPackageFile(ctx, &cran_model.SearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
FileType: cran_module.TypeSource, FileType: cran_module.TypeSource,
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
}) })
} }
@ -233,9 +233,9 @@ func DownloadBinaryPackageFile(ctx *context.Context) {
downloadPackageFile(ctx, &cran_model.SearchOptions{ downloadPackageFile(ctx, &cran_model.SearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
FileType: cran_module.TypeBinary, FileType: cran_module.TypeBinary,
Platform: ctx.Params("platform"), Platform: ctx.PathParam("platform"),
RVersion: ctx.Params("rversion"), RVersion: ctx.PathParam("rversion"),
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
}) })
} }

View File

@ -51,10 +51,10 @@ func GetRepositoryFile(ctx *context.Context) {
return return
} }
key := ctx.Params("distribution") key := ctx.PathParam("distribution")
component := ctx.Params("component") component := ctx.PathParam("component")
architecture := strings.TrimPrefix(ctx.Params("architecture"), "binary-") architecture := strings.TrimPrefix(ctx.PathParam("architecture"), "binary-")
if component != "" && architecture != "" { if component != "" && architecture != "" {
key += "|" + component + "|" + architecture key += "|" + component + "|" + architecture
} }
@ -63,7 +63,7 @@ func GetRepositoryFile(ctx *context.Context) {
ctx, ctx,
pv, pv,
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
CompositeKey: key, CompositeKey: key,
}, },
) )
@ -87,14 +87,14 @@ func GetRepositoryFileByHash(ctx *context.Context) {
return return
} }
algorithm := strings.ToLower(ctx.Params("algorithm")) algorithm := strings.ToLower(ctx.PathParam("algorithm"))
if algorithm == "md5sum" { if algorithm == "md5sum" {
algorithm = "md5" algorithm = "md5"
} }
pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{ pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{
VersionID: pv.ID, VersionID: pv.ID,
Hash: strings.ToLower(ctx.Params("hash")), Hash: strings.ToLower(ctx.PathParam("hash")),
HashAlgorithm: algorithm, HashAlgorithm: algorithm,
}) })
if err != nil { if err != nil {
@ -120,8 +120,8 @@ func GetRepositoryFileByHash(ctx *context.Context) {
} }
func UploadPackageFile(ctx *context.Context) { func UploadPackageFile(ctx *context.Context) {
distribution := strings.TrimSpace(ctx.Params("distribution")) distribution := strings.TrimSpace(ctx.PathParam("distribution"))
component := strings.TrimSpace(ctx.Params("component")) component := strings.TrimSpace(ctx.PathParam("component"))
if distribution == "" || component == "" { if distribution == "" || component == "" {
apiError(ctx, http.StatusBadRequest, "invalid distribution or component") apiError(ctx, http.StatusBadRequest, "invalid distribution or component")
return return
@ -207,8 +207,8 @@ func UploadPackageFile(ctx *context.Context) {
} }
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
name := ctx.Params("name") name := ctx.PathParam("name")
version := ctx.Params("version") version := ctx.PathParam("version")
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx, ctx,
@ -219,8 +219,8 @@ func DownloadPackageFile(ctx *context.Context) {
Version: version, Version: version,
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: fmt.Sprintf("%s_%s_%s.deb", name, version, ctx.Params("architecture")), Filename: fmt.Sprintf("%s_%s_%s.deb", name, version, ctx.PathParam("architecture")),
CompositeKey: fmt.Sprintf("%s|%s", ctx.Params("distribution"), ctx.Params("component")), CompositeKey: fmt.Sprintf("%s|%s", ctx.PathParam("distribution"), ctx.PathParam("component")),
}, },
) )
if err != nil { if err != nil {
@ -240,11 +240,11 @@ func DownloadPackageFile(ctx *context.Context) {
} }
func DeletePackageFile(ctx *context.Context) { func DeletePackageFile(ctx *context.Context) {
distribution := ctx.Params("distribution") distribution := ctx.PathParam("distribution")
component := ctx.Params("component") component := ctx.PathParam("component")
name := ctx.Params("name") name := ctx.PathParam("name")
version := ctx.Params("version") version := ctx.PathParam("version")
architecture := ctx.Params("architecture") architecture := ctx.PathParam("architecture")
owner := ctx.Package.Owner owner := ctx.Package.Owner

View File

@ -36,11 +36,11 @@ func DownloadPackageFile(ctx *context.Context) {
&packages_service.PackageInfo{ &packages_service.PackageInfo{
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
PackageType: packages_model.TypeGeneric, PackageType: packages_model.TypeGeneric,
Name: ctx.Params("packagename"), Name: ctx.PathParam("packagename"),
Version: ctx.Params("packageversion"), Version: ctx.PathParam("packageversion"),
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
}, },
) )
if err != nil { if err != nil {
@ -71,8 +71,8 @@ func isValidFileName(filename string) bool {
// UploadPackage uploads the specific generic package. // UploadPackage uploads the specific generic package.
// Duplicated packages get rejected. // Duplicated packages get rejected.
func UploadPackage(ctx *context.Context) { func UploadPackage(ctx *context.Context) {
packageName := ctx.Params("packagename") packageName := ctx.PathParam("packagename")
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
if !isValidPackageName(packageName) { if !isValidPackageName(packageName) {
apiError(ctx, http.StatusBadRequest, errors.New("invalid package name")) apiError(ctx, http.StatusBadRequest, errors.New("invalid package name"))
@ -84,7 +84,7 @@ func UploadPackage(ctx *context.Context) {
return return
} }
packageVersion := ctx.Params("packageversion") packageVersion := ctx.PathParam("packageversion")
if packageVersion != strings.TrimSpace(packageVersion) { if packageVersion != strings.TrimSpace(packageVersion) {
apiError(ctx, http.StatusBadRequest, errors.New("invalid package version")) apiError(ctx, http.StatusBadRequest, errors.New("invalid package version"))
return return
@ -150,8 +150,8 @@ func DeletePackage(ctx *context.Context) {
&packages_service.PackageInfo{ &packages_service.PackageInfo{
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
PackageType: packages_model.TypeGeneric, PackageType: packages_model.TypeGeneric,
Name: ctx.Params("packagename"), Name: ctx.PathParam("packagename"),
Version: ctx.Params("packageversion"), Version: ctx.PathParam("packageversion"),
}, },
) )
if err != nil { if err != nil {
@ -169,12 +169,12 @@ func DeletePackage(ctx *context.Context) {
// DeletePackageFile deletes the specific file of a generic package. // DeletePackageFile deletes the specific file of a generic package.
func DeletePackageFile(ctx *context.Context) { func DeletePackageFile(ctx *context.Context) {
pv, pf, err := func() (*packages_model.PackageVersion, *packages_model.PackageFile, error) { pv, pf, err := func() (*packages_model.PackageVersion, *packages_model.PackageFile, error) {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeGeneric, ctx.Params("packagename"), ctx.Params("packageversion")) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeGeneric, ctx.PathParam("packagename"), ctx.PathParam("packageversion"))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
pf, err := packages_model.GetFileForVersionByName(ctx, pv.ID, ctx.Params("filename"), packages_model.EmptyFileKey) pf, err := packages_model.GetFileForVersionByName(ctx, pv.ID, ctx.PathParam("filename"), packages_model.EmptyFileKey)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -28,7 +28,7 @@ func apiError(ctx *context.Context, status int, obj any) {
} }
func EnumeratePackageVersions(ctx *context.Context) { func EnumeratePackageVersions(ctx *context.Context) {
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeGo, ctx.Params("name")) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeGo, ctx.PathParam("name"))
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
@ -50,7 +50,7 @@ func EnumeratePackageVersions(ctx *context.Context) {
} }
func PackageVersionMetadata(ctx *context.Context) { func PackageVersionMetadata(ctx *context.Context) {
pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.Params("name"), ctx.Params("version")) pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.PathParam("name"), ctx.PathParam("version"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)
@ -70,7 +70,7 @@ func PackageVersionMetadata(ctx *context.Context) {
} }
func PackageVersionGoModContent(ctx *context.Context) { func PackageVersionGoModContent(ctx *context.Context) {
pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.Params("name"), ctx.Params("version")) pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.PathParam("name"), ctx.PathParam("version"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)
@ -90,7 +90,7 @@ func PackageVersionGoModContent(ctx *context.Context) {
} }
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.Params("name"), ctx.Params("version")) pv, err := resolvePackage(ctx, ctx.Package.Owner.ID, ctx.PathParam("name"), ctx.PathParam("version"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)

View File

@ -101,14 +101,14 @@ func Index(ctx *context.Context) {
// DownloadPackageFile serves the content of a package // DownloadPackageFile serves the content of a package
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{ pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
Type: packages_model.TypeHelm, Type: packages_model.TypeHelm,
Name: packages_model.SearchValue{ Name: packages_model.SearchValue{
ExactMatch: true, ExactMatch: true,
Value: ctx.Params("package"), Value: ctx.PathParam("package"),
}, },
HasFileWithName: filename, HasFileWithName: filename,
IsInternal: optional.Some(false), IsInternal: optional.Some(false),

View File

@ -385,7 +385,7 @@ type parameters struct {
} }
func extractPathParameters(ctx *context.Context) (parameters, error) { func extractPathParameters(ctx *context.Context) (parameters, error) {
parts := strings.Split(ctx.Params("*"), "/") parts := strings.Split(ctx.PathParam("*"), "/")
p := parameters{ p := parameters{
Filename: parts[len(parts)-1], Filename: parts[len(parts)-1],

View File

@ -43,8 +43,8 @@ func apiError(ctx *context.Context, status int, obj any) {
// packageNameFromParams gets the package name from the url parameters // packageNameFromParams gets the package name from the url parameters
// Variations: /name/, /@scope/name/, /@scope%2Fname/ // Variations: /name/, /@scope/name/, /@scope%2Fname/
func packageNameFromParams(ctx *context.Context) string { func packageNameFromParams(ctx *context.Context) string {
scope := ctx.Params("scope") scope := ctx.PathParam("scope")
id := ctx.Params("id") id := ctx.PathParam("id")
if scope != "" { if scope != "" {
return fmt.Sprintf("@%s/%s", scope, id) return fmt.Sprintf("@%s/%s", scope, id)
} }
@ -82,8 +82,8 @@ func PackageMetadata(ctx *context.Context) {
// DownloadPackageFile serves the content of a package // DownloadPackageFile serves the content of a package
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
packageName := packageNameFromParams(ctx) packageName := packageNameFromParams(ctx)
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx, ctx,
@ -111,7 +111,7 @@ func DownloadPackageFile(ctx *context.Context) {
// DownloadPackageFileByName finds the version and serves the contents of a package // DownloadPackageFileByName finds the version and serves the contents of a package
func DownloadPackageFileByName(ctx *context.Context) { func DownloadPackageFileByName(ctx *context.Context) {
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{ pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
OwnerID: ctx.Package.Owner.ID, OwnerID: ctx.Package.Owner.ID,
@ -254,7 +254,7 @@ func DeletePreview(ctx *context.Context) {
// DeletePackageVersion deletes the package version // DeletePackageVersion deletes the package version
func DeletePackageVersion(ctx *context.Context) { func DeletePackageVersion(ctx *context.Context) {
packageName := packageNameFromParams(ctx) packageName := packageNameFromParams(ctx)
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
err := packages_service.RemovePackageVersionByNameAndVersion( err := packages_service.RemovePackageVersionByNameAndVersion(
ctx, ctx,
@ -349,7 +349,7 @@ func AddPackageTag(ctx *context.Context) {
return return
} }
if err := setPackageTag(ctx, ctx.Params("tag"), pv, false); err != nil { if err := setPackageTag(ctx, ctx.PathParam("tag"), pv, false); err != nil {
if err == errInvalidTagName { if err == errInvalidTagName {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
@ -370,7 +370,7 @@ func DeletePackageTag(ctx *context.Context) {
} }
if len(pvs) != 0 { if len(pvs) != 0 {
if err := setPackageTag(ctx, ctx.Params("tag"), pvs[0], true); err != nil { if err := setPackageTag(ctx, ctx.PathParam("tag"), pvs[0], true); err != nil {
if err == errInvalidTagName { if err == errInvalidTagName {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return

View File

@ -226,7 +226,7 @@ func SearchServiceV3(ctx *context.Context) {
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index // https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index
func RegistrationIndex(ctx *context.Context) { func RegistrationIndex(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName)
if err != nil { if err != nil {
@ -254,8 +254,8 @@ func RegistrationIndex(ctx *context.Context) {
// https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedQueryBuilder.cs // https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedQueryBuilder.cs
func RegistrationLeafV2(ctx *context.Context) { func RegistrationLeafV2(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion)
if err != nil { if err != nil {
@ -283,8 +283,8 @@ func RegistrationLeafV2(ctx *context.Context) {
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf // https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf
func RegistrationLeafV3(ctx *context.Context) { func RegistrationLeafV3(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := strings.TrimSuffix(ctx.Params("version"), ".json") packageVersion := strings.TrimSuffix(ctx.PathParam("version"), ".json")
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion)
if err != nil { if err != nil {
@ -381,7 +381,7 @@ func EnumeratePackageVersionsV2Count(ctx *context.Context) {
// https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions // https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions
func EnumeratePackageVersionsV3(ctx *context.Context) { func EnumeratePackageVersionsV3(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName)
if err != nil { if err != nil {
@ -401,9 +401,9 @@ func EnumeratePackageVersionsV3(ctx *context.Context) {
// https://learn.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec // https://learn.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec
// https://learn.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg // https://learn.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx, ctx,
@ -643,9 +643,9 @@ func processUploadedFile(ctx *context.Context, expectedType nuget_module.Package
// https://github.com/dotnet/symstore/blob/main/docs/specs/Simple_Symbol_Query_Protocol.md#request // https://github.com/dotnet/symstore/blob/main/docs/specs/Simple_Symbol_Query_Protocol.md#request
func DownloadSymbolFile(ctx *context.Context) { func DownloadSymbolFile(ctx *context.Context) {
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
guid := ctx.Params("guid")[:32] guid := ctx.PathParam("guid")[:32]
filename2 := ctx.Params("filename2") filename2 := ctx.PathParam("filename2")
if filename != filename2 { if filename != filename2 {
apiError(ctx, http.StatusBadRequest, nil) apiError(ctx, http.StatusBadRequest, nil)
@ -685,8 +685,8 @@ func DownloadSymbolFile(ctx *context.Context) {
// DeletePackage hard deletes the package // DeletePackage hard deletes the package
// https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package // https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package
func DeletePackage(ctx *context.Context) { func DeletePackage(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
err := packages_service.RemovePackageVersionByNameAndVersion( err := packages_service.RemovePackageVersionByNameAndVersion(
ctx, ctx,

View File

@ -81,7 +81,7 @@ func baseURL(ctx *context.Context) string {
// https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#list-all-versions-of-a-package // https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#list-all-versions-of-a-package
func EnumeratePackageVersions(ctx *context.Context) { func EnumeratePackageVersions(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName)
if err != nil { if err != nil {
@ -119,8 +119,8 @@ func EnumeratePackageVersions(ctx *context.Context) {
// https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#deprecated-inspect-a-specific-version-of-a-package // https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#deprecated-inspect-a-specific-version-of-a-package
func PackageVersionMetadata(ctx *context.Context) { func PackageVersionMetadata(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion)
if err != nil { if err != nil {
@ -228,8 +228,8 @@ func UploadPackageFile(ctx *context.Context) {
// https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#publishing-packages // https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#publishing-packages
func FinalizePackage(ctx *context.Context) { func FinalizePackage(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
_, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion) _, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion)
if err != nil { if err != nil {
@ -253,8 +253,8 @@ func FinalizePackage(ctx *context.Context) {
// https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#deprecated-download-a-specific-version-of-a-package // https://github.com/dart-lang/pub/blob/master/doc/repository-spec-v2.md#deprecated-download-a-specific-version-of-a-package
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
packageName := ctx.Params("id") packageName := ctx.PathParam("id")
packageVersion := strings.TrimSuffix(ctx.Params("version"), ".tar.gz") packageVersion := strings.TrimSuffix(ctx.PathParam("version"), ".tar.gz")
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypePub, packageName, packageVersion)
if err != nil { if err != nil {

View File

@ -45,7 +45,7 @@ func apiError(ctx *context.Context, status int, obj any) {
// PackageMetadata returns the metadata for a single package // PackageMetadata returns the metadata for a single package
func PackageMetadata(ctx *context.Context) { func PackageMetadata(ctx *context.Context) {
packageName := normalizer.Replace(ctx.Params("id")) packageName := normalizer.Replace(ctx.PathParam("id"))
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypePyPI, packageName) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypePyPI, packageName)
if err != nil { if err != nil {
@ -76,9 +76,9 @@ func PackageMetadata(ctx *context.Context) {
// DownloadPackageFile serves the content of a package // DownloadPackageFile serves the content of a package
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
packageName := normalizer.Replace(ctx.Params("id")) packageName := normalizer.Replace(ctx.PathParam("id"))
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx, ctx,

View File

@ -33,7 +33,7 @@ func apiError(ctx *context.Context, status int, obj any) {
// https://dnf.readthedocs.io/en/latest/conf_ref.html // https://dnf.readthedocs.io/en/latest/conf_ref.html
func GetRepositoryConfig(ctx *context.Context) { func GetRepositoryConfig(ctx *context.Context) {
group := ctx.Params("group") group := ctx.PathParam("group")
var groupParts []string var groupParts []string
if group != "" { if group != "" {
@ -71,7 +71,7 @@ func CheckRepositoryFileExistence(ctx *context.Context) {
return return
} }
pf, err := packages_model.GetFileForVersionByName(ctx, pv.ID, ctx.Params("filename"), ctx.Params("group")) pf, err := packages_model.GetFileForVersionByName(ctx, pv.ID, ctx.PathParam("filename"), ctx.PathParam("group"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
ctx.Status(http.StatusNotFound) ctx.Status(http.StatusNotFound)
@ -100,8 +100,8 @@ func GetRepositoryFile(ctx *context.Context) {
ctx, ctx,
pv, pv,
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: ctx.Params("filename"), Filename: ctx.PathParam("filename"),
CompositeKey: ctx.Params("group"), CompositeKey: ctx.PathParam("group"),
}, },
) )
if err != nil { if err != nil {
@ -153,7 +153,7 @@ func UploadPackageFile(ctx *context.Context) {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
} }
group := ctx.Params("group") group := ctx.PathParam("group")
_, _, err = packages_service.CreatePackageOrAddFileToExisting( _, _, err = packages_service.CreatePackageOrAddFileToExisting(
ctx, ctx,
&packages_service.PackageCreationInfo{ &packages_service.PackageCreationInfo{
@ -202,8 +202,8 @@ func UploadPackageFile(ctx *context.Context) {
} }
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
name := ctx.Params("name") name := ctx.PathParam("name")
version := ctx.Params("version") version := ctx.PathParam("version")
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
ctx, ctx,
@ -214,8 +214,8 @@ func DownloadPackageFile(ctx *context.Context) {
Version: version, Version: version,
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: fmt.Sprintf("%s-%s.%s.rpm", name, version, ctx.Params("architecture")), Filename: fmt.Sprintf("%s-%s.%s.rpm", name, version, ctx.PathParam("architecture")),
CompositeKey: ctx.Params("group"), CompositeKey: ctx.PathParam("group"),
}, },
) )
if err != nil { if err != nil {
@ -231,10 +231,10 @@ func DownloadPackageFile(ctx *context.Context) {
} }
func DeletePackageFile(webctx *context.Context) { func DeletePackageFile(webctx *context.Context) {
group := webctx.Params("group") group := webctx.PathParam("group")
name := webctx.Params("name") name := webctx.PathParam("name")
version := webctx.Params("version") version := webctx.PathParam("version")
architecture := webctx.Params("architecture") architecture := webctx.PathParam("architecture")
var pd *packages_model.PackageDescriptor var pd *packages_model.PackageDescriptor

View File

@ -95,7 +95,7 @@ func enumeratePackages(ctx *context.Context, filename string, pvs []*packages_mo
// ServePackageSpecification serves the compressed Gemspec file of a package // ServePackageSpecification serves the compressed Gemspec file of a package
func ServePackageSpecification(ctx *context.Context) { func ServePackageSpecification(ctx *context.Context) {
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
if !strings.HasSuffix(filename, ".gemspec.rz") { if !strings.HasSuffix(filename, ".gemspec.rz") {
apiError(ctx, http.StatusNotImplemented, nil) apiError(ctx, http.StatusNotImplemented, nil)
@ -164,7 +164,7 @@ func ServePackageSpecification(ctx *context.Context) {
// DownloadPackageFile serves the content of a package // DownloadPackageFile serves the content of a package
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
filename := ctx.Params("filename") filename := ctx.PathParam("filename")
pvs, err := getVersionsByFilename(ctx, filename) pvs, err := getVersionsByFilename(ctx, filename)
if err != nil { if err != nil {
@ -299,7 +299,7 @@ func DeletePackage(ctx *context.Context) {
// GetPackageInfo returns a custom text based format for the single rubygem with a line for each version of the rubygem // GetPackageInfo returns a custom text based format for the single rubygem with a line for each version of the rubygem
// ref: https://guides.rubygems.org/rubygems-org-compact-index-api/ // ref: https://guides.rubygems.org/rubygems-org-compact-index-api/
func GetPackageInfo(ctx *context.Context) { func GetPackageInfo(ctx *context.Context) {
packageName := ctx.Params("packagename") packageName := ctx.PathParam("packagename")
versions, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeRubyGems, packageName) versions, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeRubyGems, packageName)
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)

View File

@ -115,8 +115,8 @@ type EnumeratePackageVersionsResponse struct {
// https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#41-list-package-releases // https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#41-list-package-releases
func EnumeratePackageVersions(ctx *context.Context) { func EnumeratePackageVersions(ctx *context.Context) {
packageScope := ctx.Params("scope") packageScope := ctx.PathParam("scope")
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(packageScope, packageName)) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(packageScope, packageName))
if err != nil { if err != nil {
@ -172,9 +172,9 @@ type PackageVersionMetadataResponse struct {
// https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-2 // https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-2
func PackageVersionMetadata(ctx *context.Context) { func PackageVersionMetadata(ctx *context.Context) {
id := buildPackageID(ctx.Params("scope"), ctx.Params("name")) id := buildPackageID(ctx.PathParam("scope"), ctx.PathParam("name"))
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, id, ctx.Params("version")) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, id, ctx.PathParam("version"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)
@ -230,9 +230,9 @@ func PackageVersionMetadata(ctx *context.Context) {
// https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#43-fetch-manifest-for-a-package-release // https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#43-fetch-manifest-for-a-package-release
func DownloadManifest(ctx *context.Context) { func DownloadManifest(ctx *context.Context) {
packageScope := ctx.Params("scope") packageScope := ctx.PathParam("scope")
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
packageVersion := ctx.Params("version") packageVersion := ctx.PathParam("version")
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(packageScope, packageName), packageVersion) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(packageScope, packageName), packageVersion)
if err != nil { if err != nil {
@ -282,10 +282,10 @@ func DownloadManifest(ctx *context.Context) {
// https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-6 // https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-6
func UploadPackageFile(ctx *context.Context) { func UploadPackageFile(ctx *context.Context) {
packageScope := ctx.Params("scope") packageScope := ctx.PathParam("scope")
packageName := ctx.Params("name") packageName := ctx.PathParam("name")
v, err := version.NewVersion(ctx.Params("version")) v, err := version.NewVersion(ctx.PathParam("version"))
if !scopePattern.MatchString(packageScope) || !namePattern.MatchString(packageName) || err != nil { if !scopePattern.MatchString(packageScope) || !namePattern.MatchString(packageName) || err != nil {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
@ -381,7 +381,7 @@ func UploadPackageFile(ctx *context.Context) {
// https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-4 // https://github.com/apple/swift-package-manager/blob/main/Documentation/Registry.md#endpoint-4
func DownloadPackageFile(ctx *context.Context) { func DownloadPackageFile(ctx *context.Context) {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(ctx.Params("scope"), ctx.Params("name")), ctx.Params("version")) pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeSwift, buildPackageID(ctx.PathParam("scope"), ctx.PathParam("name")), ctx.PathParam("version"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
apiError(ctx, http.StatusNotFound, err) apiError(ctx, http.StatusNotFound, err)

View File

@ -44,7 +44,7 @@ func CheckAuthenticate(ctx *context.Context) {
} }
func CheckBoxAvailable(ctx *context.Context) { func CheckBoxAvailable(ctx *context.Context) {
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeVagrant, ctx.Params("name")) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeVagrant, ctx.PathParam("name"))
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
@ -101,7 +101,7 @@ func packageDescriptorToMetadata(baseURL string, pd *packages_model.PackageDescr
} }
func EnumeratePackageVersions(ctx *context.Context) { func EnumeratePackageVersions(ctx *context.Context) {
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeVagrant, ctx.Params("name")) pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeVagrant, ctx.PathParam("name"))
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
@ -136,14 +136,14 @@ func EnumeratePackageVersions(ctx *context.Context) {
} }
func UploadPackageFile(ctx *context.Context) { func UploadPackageFile(ctx *context.Context) {
boxName := ctx.Params("name") boxName := ctx.PathParam("name")
boxVersion := ctx.Params("version") boxVersion := ctx.PathParam("version")
_, err := version.NewSemver(boxVersion) _, err := version.NewSemver(boxVersion)
if err != nil { if err != nil {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
} }
boxProvider := ctx.Params("provider") boxProvider := ctx.PathParam("provider")
if !strings.HasSuffix(boxProvider, ".box") { if !strings.HasSuffix(boxProvider, ".box") {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
@ -222,11 +222,11 @@ func DownloadPackageFile(ctx *context.Context) {
&packages_service.PackageInfo{ &packages_service.PackageInfo{
Owner: ctx.Package.Owner, Owner: ctx.Package.Owner,
PackageType: packages_model.TypeVagrant, PackageType: packages_model.TypeVagrant,
Name: ctx.Params("name"), Name: ctx.PathParam("name"),
Version: ctx.Params("version"), Version: ctx.PathParam("version"),
}, },
&packages_service.PackageFileInfo{ &packages_service.PackageFileInfo{
Filename: ctx.Params("provider"), Filename: ctx.PathParam("provider"),
}, },
) )
if err != nil { if err != nil {

View File

@ -80,8 +80,8 @@ func AdoptRepository(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
// "403": // "403":
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
ownerName := ctx.Params(":username") ownerName := ctx.PathParam(":username")
repoName := ctx.Params(":reponame") repoName := ctx.PathParam(":reponame")
ctxUser, err := user_model.GetUserByName(ctx, ownerName) ctxUser, err := user_model.GetUserByName(ctx, ownerName)
if err != nil { if err != nil {
@ -142,8 +142,8 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
// "403": // "403":
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
ownerName := ctx.Params(":username") ownerName := ctx.PathParam(":username")
repoName := ctx.Params(":reponame") repoName := ctx.PathParam(":reponame")
ctxUser, err := user_model.GetUserByName(ctx, ownerName) ctxUser, err := user_model.GetUserByName(ctx, ownerName)
if err != nil { if err != nil {

View File

@ -74,7 +74,7 @@ func PostCronTask(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
task := cron.GetTask(ctx.Params(":task")) task := cron.GetTask(ctx.PathParam(":task"))
if task == nil { if task == nil {
ctx.NotFound() ctx.NotFound()
return return

View File

@ -38,7 +38,7 @@ func GetAllEmails(ctx *context.APIContext) {
listOptions := utils.GetListOptions(ctx) listOptions := utils.GetListOptions(ctx)
emails, maxResults, err := user_model.SearchEmails(ctx, &user_model.SearchEmailOptions{ emails, maxResults, err := user_model.SearchEmails(ctx, &user_model.SearchEmailOptions{
Keyword: ctx.Params(":email"), Keyword: ctx.PathParam(":email"),
ListOptions: listOptions, ListOptions: listOptions,
}) })
if err != nil { if err != nil {
@ -82,6 +82,6 @@ func SearchEmail(ctx *context.APIContext) {
// "403": // "403":
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
ctx.SetParams(":email", ctx.FormTrim("q")) ctx.SetPathParam(":email", ctx.FormTrim("q"))
GetAllEmails(ctx) GetAllEmails(ctx)
} }

View File

@ -73,7 +73,7 @@ func GetHook(ctx *context.APIContext) {
// "200": // "200":
// "$ref": "#/responses/Hook" // "$ref": "#/responses/Hook"
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
hook, err := webhook.GetSystemOrDefaultWebhook(ctx, hookID) hook, err := webhook.GetSystemOrDefaultWebhook(ctx, hookID)
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -142,7 +142,7 @@ func EditHook(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.EditHookOption) form := web.GetForm(ctx).(*api.EditHookOption)
// TODO in body params // TODO in body params
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
utils.EditSystemHook(ctx, form, hookID) utils.EditSystemHook(ctx, form, hookID)
} }
@ -164,7 +164,7 @@ func DeleteHook(ctx *context.APIContext) {
// "204": // "204":
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
if err := webhook.DeleteDefaultSystemWebhook(ctx, hookID); err != nil { if err := webhook.DeleteDefaultSystemWebhook(ctx, hookID); err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
ctx.NotFound() ctx.NotFound()

View File

@ -373,7 +373,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := asymkey_service.DeletePublicKey(ctx, ctx.ContextUser, ctx.ParamsInt64(":id")); err != nil { if err := asymkey_service.DeletePublicKey(ctx, ctx.ContextUser, ctx.PathParamInt64(":id")); err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()
} else if asymkey_model.IsErrKeyAccessDenied(err) { } else if asymkey_model.IsErrKeyAccessDenied(err) {

View File

@ -136,8 +136,8 @@ func sudo() func(ctx *context.APIContext) {
func repoAssignment() func(ctx *context.APIContext) { func repoAssignment() func(ctx *context.APIContext) {
return func(ctx *context.APIContext) { return func(ctx *context.APIContext) {
userName := ctx.Params("username") userName := ctx.PathParam("username")
repoName := ctx.Params("reponame") repoName := ctx.PathParam("reponame")
var ( var (
owner *user_model.User owner *user_model.User
@ -555,12 +555,12 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
var err error var err error
if assignOrg { if assignOrg {
ctx.Org.Organization, err = organization.GetOrgByName(ctx, ctx.Params(":org")) ctx.Org.Organization, err = organization.GetOrgByName(ctx, ctx.PathParam(":org"))
if err != nil { if err != nil {
if organization.IsErrOrgNotExist(err) { if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(ctx, ctx.Params(":org")) redirectUserID, err := user_model.LookupUserRedirect(ctx, ctx.PathParam(":org"))
if err == nil { if err == nil {
context.RedirectToUser(ctx.Base, ctx.Params(":org"), redirectUserID) context.RedirectToUser(ctx.Base, ctx.PathParam(":org"), redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) { } else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetOrgByName", err) ctx.NotFound("GetOrgByName", err)
} else { } else {
@ -575,7 +575,7 @@ func orgAssignment(args ...bool) func(ctx *context.APIContext) {
} }
if assignTeam { if assignTeam {
ctx.Org.Team, err = organization.GetTeamByID(ctx, ctx.ParamsInt64(":teamid")) ctx.Org.Team, err = organization.GetTeamByID(ctx, ctx.PathParamInt64(":teamid"))
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -812,8 +812,8 @@ func checkDeprecatedAuthMethods(ctx *context.APIContext) {
} }
// Routes registers all v1 APIs routes to web application. // Routes registers all v1 APIs routes to web application.
func Routes() *web.Route { func Routes() *web.Router {
m := web.NewRoute() m := web.NewRouter()
m.Use(securityHeaders()) m.Use(securityHeaders())
if setting.CORSConfig.Enabled { if setting.CORSConfig.Enabled {
@ -837,7 +837,7 @@ func Routes() *web.Route {
})) }))
addActionsRoutes := func( addActionsRoutes := func(
m *web.Route, m *web.Router,
reqChecker func(ctx *context.APIContext), reqChecker func(ctx *context.APIContext),
act actions.API, act actions.API,
) { ) {

View File

@ -44,7 +44,7 @@ func GetGitignoreTemplateInfo(ctx *context.APIContext) {
// "$ref": "#/responses/GitignoreTemplateInfo" // "$ref": "#/responses/GitignoreTemplateInfo"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
name := util.PathJoinRelX(ctx.Params("name")) name := util.PathJoinRelX(ctx.PathParam("name"))
text, err := options.Gitignore(name) text, err := options.Gitignore(name)
if err != nil { if err != nil {

View File

@ -48,7 +48,7 @@ func GetLabelTemplate(ctx *context.APIContext) {
// "$ref": "#/responses/LabelTemplateInfo" // "$ref": "#/responses/LabelTemplateInfo"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
name := util.PathJoinRelX(ctx.Params("name")) name := util.PathJoinRelX(ctx.PathParam("name"))
labels, err := repo_module.LoadTemplateLabelsByDisplayName(name) labels, err := repo_module.LoadTemplateLabelsByDisplayName(name)
if err != nil { if err != nil {

View File

@ -55,7 +55,7 @@ func GetLicenseTemplateInfo(ctx *context.APIContext) {
// "$ref": "#/responses/LicenseTemplateInfo" // "$ref": "#/responses/LicenseTemplateInfo"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
name := util.PathJoinRelX(ctx.Params("name")) name := util.PathJoinRelX(ctx.PathParam("name"))
text, err := options.License(name) text, err := options.License(name)
if err != nil { if err != nil {

View File

@ -101,7 +101,7 @@ func ReadThread(ctx *context.APIContext) {
} }
func getThread(ctx *context.APIContext) *activities_model.Notification { func getThread(ctx *context.APIContext) *activities_model.Notification {
n, err := activities_model.GetNotificationByID(ctx, ctx.ParamsInt64(":id")) n, err := activities_model.GetNotificationByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
ctx.Error(http.StatusNotFound, "GetNotificationByID", err) ctx.Error(http.StatusNotFound, "GetNotificationByID", err)

View File

@ -106,7 +106,7 @@ func (Action) CreateOrUpdateSecret(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption) opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption)
_, created, err := secret_service.CreateOrUpdateSecret(ctx, ctx.Org.Organization.ID, 0, ctx.Params("secretname"), opt.Data) _, created, err := secret_service.CreateOrUpdateSecret(ctx, ctx.Org.Organization.ID, 0, ctx.PathParam("secretname"), opt.Data)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err) ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err)
@ -153,7 +153,7 @@ func (Action) DeleteSecret(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
err := secret_service.DeleteSecretByName(ctx, ctx.Org.Organization.ID, 0, ctx.Params("secretname")) err := secret_service.DeleteSecretByName(ctx, ctx.Org.Organization.ID, 0, ctx.PathParam("secretname"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteSecret", err) ctx.Error(http.StatusBadRequest, "DeleteSecret", err)
@ -269,7 +269,7 @@ func (Action) GetVariable(ctx *context.APIContext) {
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ctx.Org.Organization.ID, OwnerID: ctx.Org.Organization.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -320,7 +320,7 @@ func (Action) DeleteVariable(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := actions_service.DeleteVariableByName(ctx, ctx.Org.Organization.ID, 0, ctx.Params("variablename")); err != nil { if err := actions_service.DeleteVariableByName(ctx, ctx.Org.Organization.ID, 0, ctx.PathParam("variablename")); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err) ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err)
} else if errors.Is(err, util.ErrNotExist) { } else if errors.Is(err, util.ErrNotExist) {
@ -371,7 +371,7 @@ func (Action) CreateVariable(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateVariableOption) opt := web.GetForm(ctx).(*api.CreateVariableOption)
ownerID := ctx.Org.Organization.ID ownerID := ctx.Org.Organization.ID
variableName := ctx.Params("variablename") variableName := ctx.PathParam("variablename")
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ownerID, OwnerID: ownerID,
@ -436,7 +436,7 @@ func (Action) UpdateVariable(ctx *context.APIContext) {
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ctx.Org.Organization.ID, OwnerID: ctx.Org.Organization.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -448,7 +448,7 @@ func (Action) UpdateVariable(ctx *context.APIContext) {
} }
if opt.Name == "" { if opt.Name == "" {
opt.Name = ctx.Params("variablename") opt.Name = ctx.PathParam("variablename")
} }
if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil { if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {

View File

@ -71,7 +71,7 @@ func GetHook(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
hook, err := utils.GetOwnerHook(ctx, ctx.ContextUser.ID, ctx.ParamsInt64("id")) hook, err := utils.GetOwnerHook(ctx, ctx.ContextUser.ID, ctx.PathParamInt64("id"))
if err != nil { if err != nil {
return return
} }
@ -152,7 +152,7 @@ func EditHook(ctx *context.APIContext) {
ctx, ctx,
ctx.ContextUser, ctx.ContextUser,
web.GetForm(ctx).(*api.EditHookOption), web.GetForm(ctx).(*api.EditHookOption),
ctx.ParamsInt64("id"), ctx.PathParamInt64("id"),
) )
} }
@ -184,6 +184,6 @@ func DeleteHook(ctx *context.APIContext) {
utils.DeleteOwnerHook( utils.DeleteOwnerHook(
ctx, ctx,
ctx.ContextUser, ctx.ContextUser,
ctx.ParamsInt64("id"), ctx.PathParamInt64("id"),
) )
} }

View File

@ -139,7 +139,7 @@ func GetLabel(ctx *context.APIContext) {
label *issues_model.Label label *issues_model.Label
err error err error
) )
strID := ctx.Params(":id") strID := ctx.PathParam(":id")
if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil { if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil {
label, err = issues_model.GetLabelInOrgByName(ctx, ctx.Org.Organization.ID, strID) label, err = issues_model.GetLabelInOrgByName(ctx, ctx.Org.Organization.ID, strID)
} else { } else {
@ -190,7 +190,7 @@ func EditLabel(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption) form := web.GetForm(ctx).(*api.EditLabelOption)
l, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id")) l, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrOrgLabelNotExist(err) { if issues_model.IsErrOrgLabelNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -249,7 +249,7 @@ func DeleteLabel(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := issues_model.DeleteLabel(ctx, ctx.Org.Organization.ID, ctx.ParamsInt64(":id")); err != nil { if err := issues_model.DeleteLabel(ctx, ctx.Org.Organization.ID, ctx.PathParamInt64(":id")); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteLabel", err) ctx.Error(http.StatusInternalServerError, "DeleteLabel", err)
return return
} }

View File

@ -453,7 +453,7 @@ func GetTeamMember(ctx *context.APIContext) {
if ctx.Written() { if ctx.Written() {
return return
} }
teamID := ctx.ParamsInt64("teamid") teamID := ctx.PathParamInt64("teamid")
isTeamMember, err := organization.IsUserInTeams(ctx, u.ID, []int64{teamID}) isTeamMember, err := organization.IsUserInTeams(ctx, u.ID, []int64{teamID})
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "IsUserInTeams", err) ctx.Error(http.StatusInternalServerError, "IsUserInTeams", err)
@ -645,7 +645,7 @@ func GetTeamRepo(ctx *context.APIContext) {
// getRepositoryByParams get repository by a team's organization ID and repo name // getRepositoryByParams get repository by a team's organization ID and repo name
func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository { func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository {
repo, err := repo_model.GetRepositoryByName(ctx, ctx.Org.Team.OrgID, ctx.Params(":reponame")) repo, err := repo_model.GetRepositoryByName(ctx, ctx.Org.Team.OrgID, ctx.PathParam(":reponame"))
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -122,7 +122,7 @@ func (Action) CreateOrUpdateSecret(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption) opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption)
_, created, err := secret_service.CreateOrUpdateSecret(ctx, owner.ID, repo.ID, ctx.Params("secretname"), opt.Data) _, created, err := secret_service.CreateOrUpdateSecret(ctx, owner.ID, repo.ID, ctx.PathParam("secretname"), opt.Data)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err) ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err)
@ -177,7 +177,7 @@ func (Action) DeleteSecret(ctx *context.APIContext) {
owner := ctx.Repo.Owner owner := ctx.Repo.Owner
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
err := secret_service.DeleteSecretByName(ctx, owner.ID, repo.ID, ctx.Params("secretname")) err := secret_service.DeleteSecretByName(ctx, owner.ID, repo.ID, ctx.PathParam("secretname"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteSecret", err) ctx.Error(http.StatusBadRequest, "DeleteSecret", err)
@ -224,7 +224,7 @@ func (Action) GetVariable(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -280,7 +280,7 @@ func (Action) DeleteVariable(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := actions_service.DeleteVariableByName(ctx, 0, ctx.Repo.Repository.ID, ctx.Params("variablename")); err != nil { if err := actions_service.DeleteVariableByName(ctx, 0, ctx.Repo.Repository.ID, ctx.PathParam("variablename")); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err) ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err)
} else if errors.Is(err, util.ErrNotExist) { } else if errors.Is(err, util.ErrNotExist) {
@ -334,7 +334,7 @@ func (Action) CreateVariable(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateVariableOption) opt := web.GetForm(ctx).(*api.CreateVariableOption)
repoID := ctx.Repo.Repository.ID repoID := ctx.Repo.Repository.ID
variableName := ctx.Params("variablename") variableName := ctx.PathParam("variablename")
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
RepoID: repoID, RepoID: repoID,
@ -402,7 +402,7 @@ func (Action) UpdateVariable(ctx *context.APIContext) {
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -414,7 +414,7 @@ func (Action) UpdateVariable(ctx *context.APIContext) {
} }
if opt.Name == "" { if opt.Name == "" {
opt.Name = ctx.Params("variablename") opt.Name = ctx.PathParam("variablename")
} }
if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil { if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {

View File

@ -41,7 +41,7 @@ func GetBlob(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params("sha") sha := ctx.PathParam("sha")
if len(sha) == 0 { if len(sha) == 0 {
ctx.Error(http.StatusBadRequest, "", "sha not provided") ctx.Error(http.StatusBadRequest, "", "sha not provided")
return return

View File

@ -56,7 +56,7 @@ func GetBranch(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
branchName := ctx.Params("*") branchName := ctx.PathParam("*")
branch, err := ctx.Repo.GitRepo.GetBranch(branchName) branch, err := ctx.Repo.GitRepo.GetBranch(branchName)
if err != nil { if err != nil {
@ -131,7 +131,7 @@ func DeleteBranch(ctx *context.APIContext) {
return return
} }
branchName := ctx.Params("*") branchName := ctx.PathParam("*")
if ctx.Repo.Repository.IsEmpty { if ctx.Repo.Repository.IsEmpty {
ctx.Error(http.StatusForbidden, "", "Git Repository is empty.") ctx.Error(http.StatusForbidden, "", "Git Repository is empty.")
@ -426,7 +426,7 @@ func GetBranchProtection(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
bpName := ctx.Params(":name") bpName := ctx.PathParam(":name")
bp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName) bp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
@ -724,7 +724,7 @@ func EditBranchProtection(ctx *context.APIContext) {
// "$ref": "#/responses/repoArchivedError" // "$ref": "#/responses/repoArchivedError"
form := web.GetForm(ctx).(*api.EditBranchProtectionOption) form := web.GetForm(ctx).(*api.EditBranchProtectionOption)
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
bpName := ctx.Params(":name") bpName := ctx.PathParam(":name")
protectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName) protectBranch, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)
@ -992,7 +992,7 @@ func DeleteBranchProtection(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
bpName := ctx.Params(":name") bpName := ctx.PathParam(":name")
bp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName) bp, err := git_model.GetProtectedBranchRuleByName(ctx, repo.ID, bpName)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedBranchByID", err)

View File

@ -102,7 +102,7 @@ func IsCollaborator(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
user, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator")) user, err := user_model.GetUserByName(ctx, ctx.PathParam(":collaborator"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -162,7 +162,7 @@ func AddCollaborator(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.AddCollaboratorOption) form := web.GetForm(ctx).(*api.AddCollaboratorOption)
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator")) collaborator, err := user_model.GetUserByName(ctx, ctx.PathParam(":collaborator"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -227,7 +227,7 @@ func DeleteCollaborator(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator")) collaborator, err := user_model.GetUserByName(ctx, ctx.PathParam(":collaborator"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -275,12 +275,12 @@ func GetRepoPermissions(ctx *context.APIContext) {
// "403": // "403":
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
if !ctx.Doer.IsAdmin && ctx.Doer.LoginName != ctx.Params(":collaborator") && !ctx.IsUserRepoAdmin() { if !ctx.Doer.IsAdmin && ctx.Doer.LoginName != ctx.PathParam(":collaborator") && !ctx.IsUserRepoAdmin() {
ctx.Error(http.StatusForbidden, "User", "Only admins can query all permissions, repo admins can query all repo permissions, collaborators can query only their own") ctx.Error(http.StatusForbidden, "User", "Only admins can query all permissions, repo admins can query all repo permissions, collaborators can query only their own")
return return
} }
collaborator, err := user_model.GetUserByName(ctx, ctx.Params(":collaborator")) collaborator, err := user_model.GetUserByName(ctx, ctx.PathParam(":collaborator"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.Error(http.StatusNotFound, "GetUserByName", err) ctx.Error(http.StatusNotFound, "GetUserByName", err)

View File

@ -63,7 +63,7 @@ func GetSingleCommit(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params(":sha") sha := ctx.PathParam(":sha")
if !git.IsValidRefPattern(sha) { if !git.IsValidRefPattern(sha) {
ctx.Error(http.StatusUnprocessableEntity, "no valid ref or sha", fmt.Sprintf("no valid ref or sha: %s", sha)) ctx.Error(http.StatusUnprocessableEntity, "no valid ref or sha", fmt.Sprintf("no valid ref or sha: %s", sha))
return return
@ -312,8 +312,8 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) {
// "$ref": "#/responses/string" // "$ref": "#/responses/string"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params(":sha") sha := ctx.PathParam(":sha")
diffType := git.RawDiffType(ctx.Params(":diffType")) diffType := git.RawDiffType(ctx.PathParam(":diffType"))
if err := git.GetRawDiff(ctx.Repo.GitRepo, sha, diffType, ctx.Resp); err != nil { if err := git.GetRawDiff(ctx.Repo.GitRepo, sha, diffType, ctx.Resp); err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
@ -354,7 +354,7 @@ func GetCommitPullRequest(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByMergedCommit(ctx, ctx.Repo.Repository.ID, ctx.Params(":sha")) pr, err := issues_model.GetPullRequestByMergedCommit(ctx, ctx.Repo.Repository.ID, ctx.PathParam(":sha"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.Error(http.StatusNotFound, "GetPullRequestByMergedCommit", err) ctx.Error(http.StatusNotFound, "GetPullRequestByMergedCommit", err)

View File

@ -53,7 +53,7 @@ func CompareDiff(ctx *context.APIContext) {
defer gitRepo.Close() defer gitRepo.Close()
} }
infoPath := ctx.Params("*") infoPath := ctx.PathParam("*")
infos := []string{ctx.Repo.Repository.DefaultBranch, ctx.Repo.Repository.DefaultBranch} infos := []string{ctx.Repo.Repository.DefaultBranch, ctx.Repo.Repository.DefaultBranch}
if infoPath != "" { if infoPath != "" {
infos = strings.SplitN(infoPath, "...", 2) infos = strings.SplitN(infoPath, "...", 2)

View File

@ -294,7 +294,7 @@ func GetArchive(ctx *context.APIContext) {
} }
func archiveDownload(ctx *context.APIContext) { func archiveDownload(ctx *context.APIContext) {
uri := ctx.Params("*") uri := ctx.PathParam("*")
aReq, err := archiver_service.NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, uri) aReq, err := archiver_service.NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, uri)
if err != nil { if err != nil {
if errors.Is(err, archiver_service.ErrUnknownArchiveFormat{}) { if errors.Is(err, archiver_service.ErrUnknownArchiveFormat{}) {
@ -393,7 +393,7 @@ func GetEditorconfig(ctx *context.APIContext) {
return return
} }
fileName := ctx.Params("filename") fileName := ctx.PathParam("filename")
def, err := ec.GetDefinitionForFilename(fileName) def, err := ec.GetDefinitionForFilename(fileName)
if def == nil { if def == nil {
ctx.NotFound(err) ctx.NotFound(err)
@ -577,7 +577,7 @@ func CreateFile(ctx *context.APIContext) {
Files: []*files_service.ChangeRepoFile{ Files: []*files_service.ChangeRepoFile{
{ {
Operation: "create", Operation: "create",
TreePath: ctx.Params("*"), TreePath: ctx.PathParam("*"),
ContentReader: contentReader, ContentReader: contentReader,
}, },
}, },
@ -681,7 +681,7 @@ func UpdateFile(ctx *context.APIContext) {
ContentReader: contentReader, ContentReader: contentReader,
SHA: apiOpts.SHA, SHA: apiOpts.SHA,
FromTreePath: apiOpts.FromPath, FromTreePath: apiOpts.FromPath,
TreePath: ctx.Params("*"), TreePath: ctx.PathParam("*"),
}, },
}, },
Message: apiOpts.Message, Message: apiOpts.Message,
@ -840,7 +840,7 @@ func DeleteFile(ctx *context.APIContext) {
{ {
Operation: "delete", Operation: "delete",
SHA: apiOpts.SHA, SHA: apiOpts.SHA,
TreePath: ctx.Params("*"), TreePath: ctx.PathParam("*"),
}, },
}, },
Message: apiOpts.Message, Message: apiOpts.Message,
@ -935,7 +935,7 @@ func GetContents(ctx *context.APIContext) {
return return
} }
treePath := ctx.Params("*") treePath := ctx.PathParam("*")
ref := ctx.FormTrim("ref") ref := ctx.FormTrim("ref")
if fileList, err := files_service.GetContentsOrList(ctx, ctx.Repo.Repository, treePath, ref); err != nil { if fileList, err := files_service.GetContentsOrList(ctx, ctx.Repo.Repository, treePath, ref); err != nil {

View File

@ -79,7 +79,7 @@ func GetGitHook(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
hookID := ctx.Params(":id") hookID := ctx.PathParam(":id")
hook, err := ctx.Repo.GitRepo.GetHook(hookID) hook, err := ctx.Repo.GitRepo.GetHook(hookID)
if err != nil { if err != nil {
if err == git.ErrNotValidHook { if err == git.ErrNotValidHook {
@ -126,7 +126,7 @@ func EditGitHook(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.EditGitHookOption) form := web.GetForm(ctx).(*api.EditGitHookOption)
hookID := ctx.Params(":id") hookID := ctx.PathParam(":id")
hook, err := ctx.Repo.GitRepo.GetHook(hookID) hook, err := ctx.Repo.GitRepo.GetHook(hookID)
if err != nil { if err != nil {
if err == git.ErrNotValidHook { if err == git.ErrNotValidHook {
@ -175,7 +175,7 @@ func DeleteGitHook(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
hookID := ctx.Params(":id") hookID := ctx.PathParam(":id")
hook, err := ctx.Repo.GitRepo.GetHook(hookID) hook, err := ctx.Repo.GitRepo.GetHook(hookID)
if err != nil { if err != nil {
if err == git.ErrNotValidHook { if err == git.ErrNotValidHook {

View File

@ -71,7 +71,7 @@ func GetGitRefs(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
getGitRefsInternal(ctx, ctx.Params("*")) getGitRefsInternal(ctx, ctx.PathParam("*"))
} }
func getGitRefsInternal(ctx *context.APIContext, filter string) { func getGitRefsInternal(ctx *context.APIContext, filter string) {

View File

@ -109,7 +109,7 @@ func GetHook(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo := ctx.Repo repo := ctx.Repo
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
hook, err := utils.GetRepoHook(ctx, repo.Repository.ID, hookID) hook, err := utils.GetRepoHook(ctx, repo.Repository.ID, hookID)
if err != nil { if err != nil {
return return
@ -168,7 +168,7 @@ func TestHook(ctx *context.APIContext) {
ref = r ref = r
} }
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
hook, err := utils.GetRepoHook(ctx, ctx.Repo.Repository.ID, hookID) hook, err := utils.GetRepoHook(ctx, ctx.Repo.Repository.ID, hookID)
if err != nil { if err != nil {
return return
@ -263,7 +263,7 @@ func EditHook(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.EditHookOption) form := web.GetForm(ctx).(*api.EditHookOption)
hookID := ctx.ParamsInt64(":id") hookID := ctx.PathParamInt64(":id")
utils.EditRepoHook(ctx, form, hookID) utils.EditRepoHook(ctx, form, hookID)
} }
@ -296,7 +296,7 @@ func DeleteHook(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":id")); err != nil {
if webhook.IsErrWebhookNotExist(err) { if webhook.IsErrWebhookNotExist(err) {
ctx.NotFound() ctx.NotFound()
} else { } else {

View File

@ -18,7 +18,7 @@ func TestTestHook(t *testing.T) {
unittest.PrepareTestEnv(t) unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/wiki/_pages") ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/wiki/_pages")
ctx.SetParams(":id", "1") ctx.SetPathParam(":id", "1")
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx) contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)

View File

@ -599,7 +599,7 @@ func GetIssue(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -779,7 +779,7 @@ func EditIssue(ctx *context.APIContext) {
// "$ref": "#/responses/error" // "$ref": "#/responses/error"
form := web.GetForm(ctx).(*api.EditIssueOption) form := web.GetForm(ctx).(*api.EditIssueOption)
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -942,7 +942,7 @@ func DeleteIssue(ctx *context.APIContext) {
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -998,7 +998,7 @@ func UpdateIssueDeadline(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.EditDeadlineOption) form := web.GetForm(ctx).(*api.EditDeadlineOption)
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -320,7 +320,7 @@ func DeleteIssueAttachment(ctx *context.APIContext) {
} }
func getIssueFromContext(ctx *context.APIContext) *issues_model.Issue { func getIssueFromContext(ctx *context.APIContext) *issues_model.Issue {
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64("index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("index"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetIssueByIndex", issues_model.IsErrIssueNotExist, err) ctx.NotFoundOrServerError("GetIssueByIndex", issues_model.IsErrIssueNotExist, err)
return nil return nil
@ -345,7 +345,7 @@ func getIssueAttachmentSafeWrite(ctx *context.APIContext) *repo_model.Attachment
} }
func getIssueAttachmentSafeRead(ctx *context.APIContext, issue *issues_model.Issue) *repo_model.Attachment { func getIssueAttachmentSafeRead(ctx *context.APIContext, issue *issues_model.Issue) *repo_model.Attachment {
attachment, err := repo_model.GetAttachmentByID(ctx, ctx.ParamsInt64("attachment_id")) attachment, err := repo_model.GetAttachmentByID(ctx, ctx.PathParamInt64("attachment_id"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err) ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err)
return nil return nil

View File

@ -68,7 +68,7 @@ func ListIssueComments(ctx *context.APIContext) {
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err) ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
return return
} }
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetRawIssueByIndex", err) ctx.Error(http.StatusInternalServerError, "GetRawIssueByIndex", err)
return return
@ -172,7 +172,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err) ctx.Error(http.StatusUnprocessableEntity, "GetQueryBeforeSince", err)
return return
} }
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetRawIssueByIndex", err) ctx.Error(http.StatusInternalServerError, "GetRawIssueByIndex", err)
return return
@ -380,7 +380,7 @@ func CreateIssueComment(ctx *context.APIContext) {
// "$ref": "#/responses/repoArchivedError" // "$ref": "#/responses/repoArchivedError"
form := web.GetForm(ctx).(*api.CreateIssueCommentOption) form := web.GetForm(ctx).(*api.CreateIssueCommentOption)
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err)
return return
@ -445,7 +445,7 @@ func GetIssueComment(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64(":id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrCommentNotExist(err) { if issues_model.IsErrCommentNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -579,7 +579,7 @@ func EditIssueCommentDeprecated(ctx *context.APIContext) {
} }
func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) { func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) {
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64(":id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrCommentNotExist(err) { if issues_model.IsErrCommentNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -696,7 +696,7 @@ func DeleteIssueCommentDeprecated(ctx *context.APIContext) {
} }
func deleteIssueComment(ctx *context.APIContext) { func deleteIssueComment(ctx *context.APIContext) {
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64(":id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrCommentNotExist(err) { if issues_model.IsErrCommentNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)

View File

@ -331,7 +331,7 @@ func DeleteIssueCommentAttachment(ctx *context.APIContext) {
} }
func getIssueCommentSafe(ctx *context.APIContext) *issues_model.Comment { func getIssueCommentSafe(ctx *context.APIContext) *issues_model.Comment {
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64("id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64("id"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetCommentByID", issues_model.IsErrCommentNotExist, err) ctx.NotFoundOrServerError("GetCommentByID", issues_model.IsErrCommentNotExist, err)
return nil return nil
@ -376,7 +376,7 @@ func canUserWriteIssueCommentAttachment(ctx *context.APIContext, comment *issues
} }
func getIssueCommentAttachmentSafeRead(ctx *context.APIContext, comment *issues_model.Comment) *repo_model.Attachment { func getIssueCommentAttachmentSafeRead(ctx *context.APIContext, comment *issues_model.Comment) *repo_model.Attachment {
attachment, err := repo_model.GetAttachmentByID(ctx, ctx.ParamsInt64("attachment_id")) attachment, err := repo_model.GetAttachmentByID(ctx, ctx.PathParamInt64("attachment_id"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err) ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err)
return nil return nil

View File

@ -61,7 +61,7 @@ func GetIssueDependencies(ctx *context.APIContext) {
return return
} }
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound("IsErrIssueNotExist", err) ctx.NotFound("IsErrIssueNotExist", err)
@ -499,7 +499,7 @@ func RemoveIssueBlocking(ctx *context.APIContext) {
} }
func getParamsIssue(ctx *context.APIContext) *issues_model.Issue { func getParamsIssue(ctx *context.APIContext) *issues_model.Issue {
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound("IsErrIssueNotExist", err) ctx.NotFound("IsErrIssueNotExist", err)

View File

@ -47,7 +47,7 @@ func ListIssueLabels(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -163,7 +163,7 @@ func DeleteIssueLabel(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -178,7 +178,7 @@ func DeleteIssueLabel(ctx *context.APIContext) {
return return
} }
label, err := issues_model.GetLabelByID(ctx, ctx.ParamsInt64(":id")) label, err := issues_model.GetLabelByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrLabelNotExist(err) { if issues_model.IsErrLabelNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -285,7 +285,7 @@ func ClearIssueLabels(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -309,7 +309,7 @@ func ClearIssueLabels(ctx *context.APIContext) {
} }
func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption) (*issues_model.Issue, []*issues_model.Label, error) { func prepareForReplaceOrAdd(ctx *context.APIContext, form api.IssueLabelsOption) (*issues_model.Issue, []*issues_model.Label, error) {
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -41,7 +41,7 @@ func PinIssue(ctx *context.APIContext) {
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -98,7 +98,7 @@ func UnpinIssue(ctx *context.APIContext) {
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -159,7 +159,7 @@ func MoveIssuePin(ctx *context.APIContext) {
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -169,7 +169,7 @@ func MoveIssuePin(ctx *context.APIContext) {
return return
} }
err = issue.MovePin(ctx, int(ctx.ParamsInt64(":position"))) err = issue.MovePin(ctx, int(ctx.PathParamInt64(":position")))
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "MovePin", err) ctx.Error(http.StatusInternalServerError, "MovePin", err)
return return

View File

@ -51,7 +51,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64(":id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrCommentNotExist(err) { if issues_model.IsErrCommentNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -188,7 +188,7 @@ func DeleteIssueCommentReaction(ctx *context.APIContext) {
} }
func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOption, isCreateType bool) { func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOption, isCreateType bool) {
comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64(":id")) comment, err := issues_model.GetCommentByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrCommentNotExist(err) { if issues_model.IsErrCommentNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -295,7 +295,7 @@ func GetIssueReactions(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -419,7 +419,7 @@ func DeleteIssueReaction(ctx *context.APIContext) {
} }
func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, isCreateType bool) { func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, isCreateType bool) {
issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueWithAttrsByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -161,7 +161,7 @@ func DeleteIssueStopwatch(ctx *context.APIContext) {
} }
func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*issues_model.Issue, error) { func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*issues_model.Issue, error) {
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -104,7 +104,7 @@ func DelIssueSubscription(ctx *context.APIContext) {
} }
func setIssueSubscription(ctx *context.APIContext, watch bool) { func setIssueSubscription(ctx *context.APIContext, watch bool) {
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -115,7 +115,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) {
return return
} }
user, err := user_model.GetUserByName(ctx, ctx.Params(":user")) user, err := user_model.GetUserByName(ctx, ctx.PathParam(":user"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -185,7 +185,7 @@ func CheckIssueSubscription(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -251,7 +251,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -75,7 +75,7 @@ func ListTrackedTimes(ctx *context.APIContext) {
ctx.NotFound("Timetracker is disabled") ctx.NotFound("Timetracker is disabled")
return return
} }
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -181,7 +181,7 @@ func AddTime(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.AddTimeOption) form := web.GetForm(ctx).(*api.AddTimeOption)
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -264,7 +264,7 @@ func ResetIssueTime(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -337,7 +337,7 @@ func DeleteTime(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrIssueNotExist(err) { if issues_model.IsErrIssueNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -356,7 +356,7 @@ func DeleteTime(ctx *context.APIContext) {
return return
} }
time, err := issues_model.GetTrackedTimeByID(ctx, ctx.ParamsInt64(":id")) time, err := issues_model.GetTrackedTimeByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if db.IsErrNotExist(err) { if db.IsErrNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)
@ -422,7 +422,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) {
ctx.Error(http.StatusBadRequest, "", "time tracking disabled") ctx.Error(http.StatusBadRequest, "", "time tracking disabled")
return return
} }
user, err := user_model.GetUserByName(ctx, ctx.Params(":timetrackingusername")) user, err := user_model.GetUserByName(ctx, ctx.PathParam(":timetrackingusername"))
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {
ctx.NotFound(err) ctx.NotFound(err)

View File

@ -143,7 +143,7 @@ func GetDeployKey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
key, err := asymkey_model.GetDeployKeyByID(ctx, ctx.ParamsInt64(":id")) key, err := asymkey_model.GetDeployKeyByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if asymkey_model.IsErrDeployKeyNotExist(err) { if asymkey_model.IsErrDeployKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -279,7 +279,7 @@ func DeleteDeploykey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := asymkey_service.DeleteDeployKey(ctx, ctx.Doer, ctx.ParamsInt64(":id")); err != nil { if err := asymkey_service.DeleteDeployKey(ctx, ctx.Doer, ctx.PathParamInt64(":id")); err != nil {
if asymkey_model.IsErrKeyAccessDenied(err) { if asymkey_model.IsErrKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key") ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else { } else {

View File

@ -99,7 +99,7 @@ func GetLabel(ctx *context.APIContext) {
l *issues_model.Label l *issues_model.Label
err error err error
) )
strID := ctx.Params(":id") strID := ctx.PathParam(":id")
if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil { if intID, err2 := strconv.ParseInt(strID, 10, 64); err2 != nil {
l, err = issues_model.GetLabelInRepoByName(ctx, ctx.Repo.Repository.ID, strID) l, err = issues_model.GetLabelInRepoByName(ctx, ctx.Repo.Repository.ID, strID)
} else { } else {
@ -212,7 +212,7 @@ func EditLabel(ctx *context.APIContext) {
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditLabelOption) form := web.GetForm(ctx).(*api.EditLabelOption)
l, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) l, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrRepoLabelNotExist(err) { if issues_model.IsErrRepoLabelNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -276,7 +276,7 @@ func DeleteLabel(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := issues_model.DeleteLabel(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if err := issues_model.DeleteLabel(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":id")); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteLabel", err) ctx.Error(http.StatusInternalServerError, "DeleteLabel", err)
return return
} }

View File

@ -282,7 +282,7 @@ func DeleteMilestone(ctx *context.APIContext) {
// getMilestoneByIDOrName get milestone by ID and if not available by name // getMilestoneByIDOrName get milestone by ID and if not available by name
func getMilestoneByIDOrName(ctx *context.APIContext) *issues_model.Milestone { func getMilestoneByIDOrName(ctx *context.APIContext) *issues_model.Milestone {
mile := ctx.Params(":id") mile := ctx.PathParam(":id")
mileID, _ := strconv.ParseInt(mile, 0, 64) mileID, _ := strconv.ParseInt(mile, 0, 64)
if mileID != 0 { if mileID != 0 {

View File

@ -224,7 +224,7 @@ func GetPushMirrorByName(ctx *context.APIContext) {
return return
} }
mirrorName := ctx.Params(":name") mirrorName := ctx.PathParam(":name")
// Get push mirror of a specific repo by remoteName // Get push mirror of a specific repo by remoteName
pushMirror, exist, err := db.Get[repo_model.PushMirror](ctx, repo_model.PushMirrorOptions{ pushMirror, exist, err := db.Get[repo_model.PushMirror](ctx, repo_model.PushMirrorOptions{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
@ -325,7 +325,7 @@ func DeletePushMirrorByRemoteName(ctx *context.APIContext) {
return return
} }
remoteName := ctx.Params(":name") remoteName := ctx.PathParam(":name")
// Delete push mirror on repo by name. // Delete push mirror on repo by name.
err := repo_model.DeletePushMirrors(ctx, repo_model.PushMirrorOptions{RepoID: ctx.Repo.Repository.ID, RemoteName: remoteName}) err := repo_model.DeletePushMirrors(ctx, repo_model.PushMirrorOptions{RepoID: ctx.Repo.Repository.ID, RemoteName: remoteName})
if err != nil { if err != nil {

View File

@ -52,7 +52,7 @@ func GetNote(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params(":sha") sha := ctx.PathParam(":sha")
if !git.IsValidRefPattern(sha) { if !git.IsValidRefPattern(sha) {
ctx.Error(http.StatusUnprocessableEntity, "no valid ref or sha", fmt.Sprintf("no valid ref or sha: %s", sha)) ctx.Error(http.StatusUnprocessableEntity, "no valid ref or sha", fmt.Sprintf("no valid ref or sha: %s", sha))
return return

View File

@ -187,7 +187,7 @@ func GetPullRequest(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -244,7 +244,7 @@ func GetPullRequestByBaseHead(ctx *context.APIContext) {
var headRepoID int64 var headRepoID int64
var headBranch string var headBranch string
head := ctx.Params("*") head := ctx.PathParam("*")
if strings.Contains(head, ":") { if strings.Contains(head, ":") {
split := strings.SplitN(head, ":", 2) split := strings.SplitN(head, ":", 2)
headBranch = split[1] headBranch = split[1]
@ -272,7 +272,7 @@ func GetPullRequestByBaseHead(ctx *context.APIContext) {
headBranch = head headBranch = head
} }
pr, err := issues_model.GetPullRequestByBaseHeadInfo(ctx, ctx.Repo.Repository.ID, headRepoID, ctx.Params(":base"), headBranch) pr, err := issues_model.GetPullRequestByBaseHeadInfo(ctx, ctx.Repo.Repository.ID, headRepoID, ctx.PathParam(":base"), headBranch)
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -332,7 +332,7 @@ func DownloadPullDiffOrPatch(ctx *context.APIContext) {
// "$ref": "#/responses/string" // "$ref": "#/responses/string"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -342,7 +342,7 @@ func DownloadPullDiffOrPatch(ctx *context.APIContext) {
return return
} }
var patch bool var patch bool
if ctx.Params(":diffType") == "diff" { if ctx.PathParam(":diffType") == "diff" {
patch = false patch = false
} else { } else {
patch = true patch = true
@ -590,7 +590,7 @@ func EditPullRequest(ctx *context.APIContext) {
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.EditPullRequestOption) form := web.GetForm(ctx).(*api.EditPullRequestOption)
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -804,7 +804,7 @@ func IsPullRequestMerged(ctx *context.APIContext) {
// "404": // "404":
// description: pull request has not been merged // description: pull request has not been merged
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -862,7 +862,7 @@ func MergePullRequest(ctx *context.APIContext) {
form := web.GetForm(ctx).(*forms.MergePullRequestForm) form := web.GetForm(ctx).(*forms.MergePullRequestForm)
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err) ctx.NotFound("GetPullRequestByIndex", err)
@ -1221,7 +1221,7 @@ func UpdatePullRequest(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -1320,7 +1320,7 @@ func CancelScheduledAutoMerge(ctx *context.APIContext) {
// "423": // "423":
// "$ref": "#/responses/repoArchivedError" // "$ref": "#/responses/repoArchivedError"
pullIndex := ctx.ParamsInt64(":index") pullIndex := ctx.PathParamInt64(":index")
pull, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pullIndex) pull, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pullIndex)
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
@ -1406,7 +1406,7 @@ func GetPullRequestCommits(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -1529,7 +1529,7 @@ func GetPullRequestFiles(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -61,7 +61,7 @@ func ListPullReviews(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err) ctx.NotFound("GetPullRequestByIndex", err)
@ -307,7 +307,7 @@ func CreatePullReview(ctx *context.APIContext) {
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
opts := web.GetForm(ctx).(*api.CreatePullReviewOptions) opts := web.GetForm(ctx).(*api.CreatePullReviewOptions)
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err) ctx.NotFound("GetPullRequestByIndex", err)
@ -534,7 +534,7 @@ func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest
// prepareSingleReview return review, related pull and false or nil, nil and true if an error happen // prepareSingleReview return review, related pull and false or nil, nil and true if an error happen
func prepareSingleReview(ctx *context.APIContext) (*issues_model.Review, *issues_model.PullRequest, bool) { func prepareSingleReview(ctx *context.APIContext) (*issues_model.Review, *issues_model.PullRequest, bool) {
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err) ctx.NotFound("GetPullRequestByIndex", err)
@ -544,7 +544,7 @@ func prepareSingleReview(ctx *context.APIContext) (*issues_model.Review, *issues
return nil, nil, true return nil, nil, true
} }
review, err := issues_model.GetReviewByID(ctx, ctx.ParamsInt64(":id")) review, err := issues_model.GetReviewByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if issues_model.IsErrReviewNotExist(err) { if issues_model.IsErrReviewNotExist(err) {
ctx.NotFound("GetReviewByID", err) ctx.NotFound("GetReviewByID", err)
@ -658,7 +658,7 @@ func DeleteReviewRequests(ctx *context.APIContext) {
} }
func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions, isAdd bool) { func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions, isAdd bool) {
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64(":index"))
if err != nil { if err != nil {
if issues_model.IsErrPullRequestNotExist(err) { if issues_model.IsErrPullRequestNotExist(err) {
ctx.NotFound("GetPullRequestByIndex", err) ctx.NotFound("GetPullRequestByIndex", err)

View File

@ -50,7 +50,7 @@ func GetRelease(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
release, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id) release, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id)
if err != nil && !repo_model.IsErrReleaseNotExist(err) { if err != nil && !repo_model.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err) ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err)
@ -317,7 +317,7 @@ func EditRelease(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.EditReleaseOption) form := web.GetForm(ctx).(*api.EditReleaseOption)
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
rel, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id) rel, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id)
if err != nil && !repo_model.IsErrReleaseNotExist(err) { if err != nil && !repo_model.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err) ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err)
@ -394,7 +394,7 @@ func DeleteRelease(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
rel, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id) rel, err := repo_model.GetReleaseForRepoByID(ctx, ctx.Repo.Repository.ID, id)
if err != nil && !repo_model.IsErrReleaseNotExist(err) { if err != nil && !repo_model.IsErrReleaseNotExist(err) {
ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err) ctx.Error(http.StatusInternalServerError, "GetReleaseForRepoByID", err)

View File

@ -72,12 +72,12 @@ func GetReleaseAttachment(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
releaseID := ctx.ParamsInt64(":id") releaseID := ctx.PathParamInt64(":id")
if !checkReleaseMatchRepo(ctx, releaseID) { if !checkReleaseMatchRepo(ctx, releaseID) {
return return
} }
attachID := ctx.ParamsInt64(":attachment_id") attachID := ctx.PathParamInt64(":attachment_id")
attach, err := repo_model.GetAttachmentByID(ctx, attachID) attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil { if err != nil {
if repo_model.IsErrAttachmentNotExist(err) { if repo_model.IsErrAttachmentNotExist(err) {
@ -126,7 +126,7 @@ func ListReleaseAttachments(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
releaseID := ctx.ParamsInt64(":id") releaseID := ctx.PathParamInt64(":id")
release, err := repo_model.GetReleaseByID(ctx, releaseID) release, err := repo_model.GetReleaseByID(ctx, releaseID)
if err != nil { if err != nil {
if repo_model.IsErrReleaseNotExist(err) { if repo_model.IsErrReleaseNotExist(err) {
@ -199,7 +199,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
} }
// Check if release exists an load release // Check if release exists an load release
releaseID := ctx.ParamsInt64(":id") releaseID := ctx.PathParamInt64(":id")
if !checkReleaseMatchRepo(ctx, releaseID) { if !checkReleaseMatchRepo(ctx, releaseID) {
return return
} }
@ -297,12 +297,12 @@ func EditReleaseAttachment(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.EditAttachmentOptions) form := web.GetForm(ctx).(*api.EditAttachmentOptions)
// Check if release exists an load release // Check if release exists an load release
releaseID := ctx.ParamsInt64(":id") releaseID := ctx.PathParamInt64(":id")
if !checkReleaseMatchRepo(ctx, releaseID) { if !checkReleaseMatchRepo(ctx, releaseID) {
return return
} }
attachID := ctx.ParamsInt64(":attachment_id") attachID := ctx.PathParamInt64(":attachment_id")
attach, err := repo_model.GetAttachmentByID(ctx, attachID) attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil { if err != nil {
if repo_model.IsErrAttachmentNotExist(err) { if repo_model.IsErrAttachmentNotExist(err) {
@ -365,12 +365,12 @@ func DeleteReleaseAttachment(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
// Check if release exists an load release // Check if release exists an load release
releaseID := ctx.ParamsInt64(":id") releaseID := ctx.PathParamInt64(":id")
if !checkReleaseMatchRepo(ctx, releaseID) { if !checkReleaseMatchRepo(ctx, releaseID) {
return return
} }
attachID := ctx.ParamsInt64(":attachment_id") attachID := ctx.PathParamInt64(":attachment_id")
attach, err := repo_model.GetAttachmentByID(ctx, attachID) attach, err := repo_model.GetAttachmentByID(ctx, attachID)
if err != nil { if err != nil {
if repo_model.IsErrAttachmentNotExist(err) { if repo_model.IsErrAttachmentNotExist(err) {

View File

@ -42,7 +42,7 @@ func GetReleaseByTag(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
tag := ctx.Params(":tag") tag := ctx.PathParam(":tag")
release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag) release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag)
if err != nil { if err != nil {
@ -95,7 +95,7 @@ func DeleteReleaseByTag(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
tag := ctx.Params(":tag") tag := ctx.PathParam(":tag")
release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag) release, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tag)
if err != nil { if err != nil {

View File

@ -491,7 +491,7 @@ func CreateOrgRepo(ctx *context.APIContext) {
// "403": // "403":
// "$ref": "#/responses/forbidden" // "$ref": "#/responses/forbidden"
opt := web.GetForm(ctx).(*api.CreateRepoOption) opt := web.GetForm(ctx).(*api.CreateRepoOption)
org, err := organization.GetOrgByName(ctx, ctx.Params(":org")) org, err := organization.GetOrgByName(ctx, ctx.PathParam(":org"))
if err != nil { if err != nil {
if organization.IsErrOrgNotExist(err) { if organization.IsErrOrgNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)
@ -571,7 +571,7 @@ func GetByID(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo, err := repo_model.GetRepositoryByID(ctx, ctx.ParamsInt64(":id")) repo, err := repo_model.GetRepositoryByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -53,7 +53,7 @@ func NewCommitStatus(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
form := web.GetForm(ctx).(*api.CreateStatusOption) form := web.GetForm(ctx).(*api.CreateStatusOption)
sha := ctx.Params("sha") sha := ctx.PathParam("sha")
if len(sha) == 0 { if len(sha) == 0 {
ctx.Error(http.StatusBadRequest, "sha not given", nil) ctx.Error(http.StatusBadRequest, "sha not given", nil)
return return
@ -123,7 +123,7 @@ func GetCommitStatuses(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
getCommitStatuses(ctx, ctx.Params("sha")) getCommitStatuses(ctx, ctx.PathParam("sha"))
} }
// GetCommitStatusesByRef returns all statuses for any given commit ref // GetCommitStatusesByRef returns all statuses for any given commit ref
@ -177,7 +177,7 @@ func GetCommitStatusesByRef(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
filter := utils.ResolveRefOrSha(ctx, ctx.Params("ref")) filter := utils.ResolveRefOrSha(ctx, ctx.PathParam("ref"))
if ctx.Written() { if ctx.Written() {
return return
} }
@ -257,7 +257,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := utils.ResolveRefOrSha(ctx, ctx.Params("ref")) sha := utils.ResolveRefOrSha(ctx, ctx.PathParam("ref"))
if ctx.Written() { if ctx.Written() {
return return
} }

View File

@ -102,7 +102,7 @@ func GetAnnotatedTag(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params("sha") sha := ctx.PathParam("sha")
if len(sha) == 0 { if len(sha) == 0 {
ctx.Error(http.StatusBadRequest, "", "SHA not provided") ctx.Error(http.StatusBadRequest, "", "SHA not provided")
return return
@ -147,7 +147,7 @@ func GetTag(ctx *context.APIContext) {
// "$ref": "#/responses/Tag" // "$ref": "#/responses/Tag"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
tagName := ctx.Params("*") tagName := ctx.PathParam("*")
tag, err := ctx.Repo.GitRepo.GetTag(tagName) tag, err := ctx.Repo.GitRepo.GetTag(tagName)
if err != nil { if err != nil {
@ -263,7 +263,7 @@ func DeleteTag(ctx *context.APIContext) {
// "$ref": "#/responses/validationError" // "$ref": "#/responses/validationError"
// "423": // "423":
// "$ref": "#/responses/repoArchivedError" // "$ref": "#/responses/repoArchivedError"
tagName := ctx.Params("*") tagName := ctx.PathParam("*")
tag, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName) tag, err := repo_model.GetRelease(ctx, ctx.Repo.Repository.ID, tagName)
if err != nil { if err != nil {
@ -358,7 +358,7 @@ func GetTagProtection(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
pt, err := git_model.GetProtectedTagByID(ctx, id) pt, err := git_model.GetProtectedTagByID(ctx, id)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err)
@ -522,7 +522,7 @@ func EditTagProtection(ctx *context.APIContext) {
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
form := web.GetForm(ctx).(*api.EditTagProtectionOption) form := web.GetForm(ctx).(*api.EditTagProtectionOption)
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
pt, err := git_model.GetProtectedTagByID(ctx, id) pt, err := git_model.GetProtectedTagByID(ctx, id)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err)
@ -617,7 +617,7 @@ func DeleteTagProtection(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
repo := ctx.Repo.Repository repo := ctx.Repo.Repository
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
pt, err := git_model.GetProtectedTagByID(ctx, id) pt, err := git_model.GetProtectedTagByID(ctx, id)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err) ctx.Error(http.StatusInternalServerError, "GetProtectedTagByID", err)

View File

@ -222,7 +222,7 @@ func changeRepoTeam(ctx *context.APIContext, add bool) {
} }
func getTeamByParam(ctx *context.APIContext) *organization.Team { func getTeamByParam(ctx *context.APIContext) *organization.Team {
team, err := organization.GetTeam(ctx, ctx.Repo.Owner.ID, ctx.Params(":team")) team, err := organization.GetTeam(ctx, ctx.Repo.Owner.ID, ctx.PathParam(":team"))
if err != nil { if err != nil {
if organization.IsErrTeamNotExist(err) { if organization.IsErrTeamNotExist(err) {
ctx.Error(http.StatusNotFound, "TeamNotExit", err) ctx.Error(http.StatusNotFound, "TeamNotExit", err)

View File

@ -162,7 +162,7 @@ func AddTopic(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/invalidTopicsError" // "$ref": "#/responses/invalidTopicsError"
topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) topicName := strings.TrimSpace(strings.ToLower(ctx.PathParam(":topic")))
if !repo_model.ValidateTopic(topicName) { if !repo_model.ValidateTopic(topicName) {
ctx.JSON(http.StatusUnprocessableEntity, map[string]any{ ctx.JSON(http.StatusUnprocessableEntity, map[string]any{
@ -229,7 +229,7 @@ func DeleteTopic(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/invalidTopicsError" // "$ref": "#/responses/invalidTopicsError"
topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) topicName := strings.TrimSpace(strings.ToLower(ctx.PathParam(":topic")))
if !repo_model.ValidateTopic(topicName) { if !repo_model.ValidateTopic(topicName) {
ctx.JSON(http.StatusUnprocessableEntity, map[string]any{ ctx.JSON(http.StatusUnprocessableEntity, map[string]any{

View File

@ -56,7 +56,7 @@ func GetTree(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
sha := ctx.Params(":sha") sha := ctx.PathParam(":sha")
if len(sha) == 0 { if len(sha) == 0 {
ctx.Error(http.StatusBadRequest, "", "sha not provided") ctx.Error(http.StatusBadRequest, "", "sha not provided")
return return

View File

@ -40,7 +40,7 @@ func ListBlocks(ctx *context.APIContext, blocker *user_model.User) {
} }
func CheckUserBlock(ctx *context.APIContext, blocker *user_model.User) { func CheckUserBlock(ctx *context.APIContext, blocker *user_model.User) {
blockee, err := user_model.GetUserByName(ctx, ctx.Params("username")) blockee, err := user_model.GetUserByName(ctx, ctx.PathParam("username"))
if err != nil { if err != nil {
ctx.NotFound("GetUserByName", err) ctx.NotFound("GetUserByName", err)
return return
@ -60,7 +60,7 @@ func CheckUserBlock(ctx *context.APIContext, blocker *user_model.User) {
} }
func BlockUser(ctx *context.APIContext, blocker *user_model.User) { func BlockUser(ctx *context.APIContext, blocker *user_model.User) {
blockee, err := user_model.GetUserByName(ctx, ctx.Params("username")) blockee, err := user_model.GetUserByName(ctx, ctx.PathParam("username"))
if err != nil { if err != nil {
ctx.NotFound("GetUserByName", err) ctx.NotFound("GetUserByName", err)
return return
@ -79,7 +79,7 @@ func BlockUser(ctx *context.APIContext, blocker *user_model.User) {
} }
func UnblockUser(ctx *context.APIContext, doer, blocker *user_model.User) { func UnblockUser(ctx *context.APIContext, doer, blocker *user_model.User) {
blockee, err := user_model.GetUserByName(ctx, ctx.Params("username")) blockee, err := user_model.GetUserByName(ctx, ctx.PathParam("username"))
if err != nil { if err != nil {
ctx.NotFound("GetUserByName", err) ctx.NotFound("GetUserByName", err)
return return

View File

@ -49,7 +49,7 @@ func CreateOrUpdateSecret(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption) opt := web.GetForm(ctx).(*api.CreateOrUpdateSecretOption)
_, created, err := secret_service.CreateOrUpdateSecret(ctx, ctx.Doer.ID, 0, ctx.Params("secretname"), opt.Data) _, created, err := secret_service.CreateOrUpdateSecret(ctx, ctx.Doer.ID, 0, ctx.PathParam("secretname"), opt.Data)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err) ctx.Error(http.StatusBadRequest, "CreateOrUpdateSecret", err)
@ -91,7 +91,7 @@ func DeleteSecret(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
err := secret_service.DeleteSecretByName(ctx, ctx.Doer.ID, 0, ctx.Params("secretname")) err := secret_service.DeleteSecretByName(ctx, ctx.Doer.ID, 0, ctx.PathParam("secretname"))
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteSecret", err) ctx.Error(http.StatusBadRequest, "DeleteSecret", err)
@ -138,7 +138,7 @@ func CreateVariable(ctx *context.APIContext) {
opt := web.GetForm(ctx).(*api.CreateVariableOption) opt := web.GetForm(ctx).(*api.CreateVariableOption)
ownerID := ctx.Doer.ID ownerID := ctx.Doer.ID
variableName := ctx.Params("variablename") variableName := ctx.PathParam("variablename")
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ownerID, OwnerID: ownerID,
@ -198,7 +198,7 @@ func UpdateVariable(ctx *context.APIContext) {
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ctx.Doer.ID, OwnerID: ctx.Doer.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {
@ -210,7 +210,7 @@ func UpdateVariable(ctx *context.APIContext) {
} }
if opt.Name == "" { if opt.Name == "" {
opt.Name = ctx.Params("variablename") opt.Name = ctx.PathParam("variablename")
} }
if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil { if _, err := actions_service.UpdateVariable(ctx, v.ID, opt.Name, opt.Value); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
@ -247,7 +247,7 @@ func DeleteVariable(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
if err := actions_service.DeleteVariableByName(ctx, ctx.Doer.ID, 0, ctx.Params("variablename")); err != nil { if err := actions_service.DeleteVariableByName(ctx, ctx.Doer.ID, 0, ctx.PathParam("variablename")); err != nil {
if errors.Is(err, util.ErrInvalidArgument) { if errors.Is(err, util.ErrInvalidArgument) {
ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err) ctx.Error(http.StatusBadRequest, "DeleteVariableByName", err)
} else if errors.Is(err, util.ErrNotExist) { } else if errors.Is(err, util.ErrNotExist) {
@ -284,7 +284,7 @@ func GetVariable(ctx *context.APIContext) {
v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{ v, err := actions_service.GetVariable(ctx, actions_model.FindVariablesOpts{
OwnerID: ctx.Doer.ID, OwnerID: ctx.Doer.ID,
Name: ctx.Params("variablename"), Name: ctx.PathParam("variablename"),
}) })
if err != nil { if err != nil {
if errors.Is(err, util.ErrNotExist) { if errors.Is(err, util.ErrNotExist) {

View File

@ -160,7 +160,7 @@ func DeleteAccessToken(ctx *context.APIContext) {
// "422": // "422":
// "$ref": "#/responses/error" // "$ref": "#/responses/error"
token := ctx.Params(":id") token := ctx.PathParam(":id")
tokenID, _ := strconv.ParseInt(token, 0, 64) tokenID, _ := strconv.ParseInt(token, 0, 64)
if tokenID == 0 { if tokenID == 0 {
@ -300,7 +300,7 @@ func DeleteOauth2Application(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
appID := ctx.ParamsInt64(":id") appID := ctx.PathParamInt64(":id")
if err := auth_model.DeleteOAuth2Application(ctx, appID, ctx.Doer.ID); err != nil { if err := auth_model.DeleteOAuth2Application(ctx, appID, ctx.Doer.ID); err != nil {
if auth_model.IsErrOAuthApplicationNotFound(err) { if auth_model.IsErrOAuthApplicationNotFound(err) {
ctx.NotFound() ctx.NotFound()
@ -332,7 +332,7 @@ func GetOauth2Application(ctx *context.APIContext) {
// "$ref": "#/responses/OAuth2Application" // "$ref": "#/responses/OAuth2Application"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
appID := ctx.ParamsInt64(":id") appID := ctx.PathParamInt64(":id")
app, err := auth_model.GetOAuth2ApplicationByID(ctx, appID) app, err := auth_model.GetOAuth2ApplicationByID(ctx, appID)
if err != nil { if err != nil {
if auth_model.IsErrOauthClientIDInvalid(err) || auth_model.IsErrOAuthApplicationNotFound(err) { if auth_model.IsErrOauthClientIDInvalid(err) || auth_model.IsErrOAuthApplicationNotFound(err) {
@ -376,7 +376,7 @@ func UpdateOauth2Application(ctx *context.APIContext) {
// "$ref": "#/responses/OAuth2Application" // "$ref": "#/responses/OAuth2Application"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
appID := ctx.ParamsInt64(":id") appID := ctx.PathParamInt64(":id")
data := web.GetForm(ctx).(*api.CreateOAuth2ApplicationOptions) data := web.GetForm(ctx).(*api.CreateOAuth2ApplicationOptions)

View File

@ -116,7 +116,7 @@ func GetGPGKey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
key, err := asymkey_model.GetGPGKeyForUserByID(ctx, ctx.Doer.ID, ctx.ParamsInt64(":id")) key, err := asymkey_model.GetGPGKeyForUserByID(ctx, ctx.Doer.ID, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if asymkey_model.IsErrGPGKeyNotExist(err) { if asymkey_model.IsErrGPGKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -280,7 +280,7 @@ func DeleteGPGKey(ctx *context.APIContext) {
return return
} }
if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.ParamsInt64(":id")); err != nil { if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.PathParamInt64(":id")); err != nil {
if asymkey_model.IsErrGPGKeyAccessDenied(err) { if asymkey_model.IsErrGPGKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key") ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else { } else {

View File

@ -12,7 +12,7 @@ import (
// GetUserByParamsName get user by name // GetUserByParamsName get user by name
func GetUserByParamsName(ctx *context.APIContext, name string) *user_model.User { func GetUserByParamsName(ctx *context.APIContext, name string) *user_model.User {
username := ctx.Params(name) username := ctx.PathParam(name)
user, err := user_model.GetUserByName(ctx, username) user, err := user_model.GetUserByName(ctx, username)
if err != nil { if err != nil {
if user_model.IsErrUserNotExist(err) { if user_model.IsErrUserNotExist(err) {

View File

@ -57,7 +57,7 @@ func GetHook(ctx *context.APIContext) {
// "200": // "200":
// "$ref": "#/responses/Hook" // "$ref": "#/responses/Hook"
hook, err := utils.GetOwnerHook(ctx, ctx.Doer.ID, ctx.ParamsInt64("id")) hook, err := utils.GetOwnerHook(ctx, ctx.Doer.ID, ctx.PathParamInt64("id"))
if err != nil { if err != nil {
return return
} }
@ -129,7 +129,7 @@ func EditHook(ctx *context.APIContext) {
ctx, ctx,
ctx.Doer, ctx.Doer,
web.GetForm(ctx).(*api.EditHookOption), web.GetForm(ctx).(*api.EditHookOption),
ctx.ParamsInt64("id"), ctx.PathParamInt64("id"),
) )
} }
@ -154,6 +154,6 @@ func DeleteHook(ctx *context.APIContext) {
utils.DeleteOwnerHook( utils.DeleteOwnerHook(
ctx, ctx,
ctx.Doer, ctx.Doer,
ctx.ParamsInt64("id"), ctx.PathParamInt64("id"),
) )
} }

View File

@ -55,7 +55,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
var count int var count int
fingerprint := ctx.FormString("fingerprint") fingerprint := ctx.FormString("fingerprint")
username := ctx.Params("username") username := ctx.PathParam("username")
if fingerprint != "" { if fingerprint != "" {
var userID int64 // Unrestricted var userID int64 // Unrestricted
@ -179,7 +179,7 @@ func GetPublicKey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.ParamsInt64(":id")) key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.PathParamInt64(":id"))
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -274,7 +274,7 @@ func DeletePublicKey(ctx *context.APIContext) {
return return
} }
id := ctx.ParamsInt64(":id") id := ctx.PathParamInt64(":id")
externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id) externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id)
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {

View File

@ -113,7 +113,7 @@ func GetInfo(ctx *context.APIContext) {
if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) { if !user_model.IsUserVisibleToViewer(ctx, ctx.ContextUser, ctx.Doer) {
// fake ErrUserNotExist error message to not leak information about existence // fake ErrUserNotExist error message to not leak information about existence
ctx.NotFound("GetUserByName", user_model.ErrUserNotExist{Name: ctx.Params(":username")}) ctx.NotFound("GetUserByName", user_model.ErrUserNotExist{Name: ctx.PathParam(":username")})
return return
} }
ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer)) ctx.JSON(http.StatusOK, convert.ToUser(ctx, ctx.ContextUser, ctx.Doer))

View File

@ -177,9 +177,9 @@ func InitWebInstalled(ctx context.Context) {
} }
// NormalRoutes represents non install routes // NormalRoutes represents non install routes
func NormalRoutes() *web.Route { func NormalRoutes() *web.Router {
_ = templates.HTMLRenderer() _ = templates.HTMLRenderer()
r := web.NewRoute() r := web.NewRouter()
r.Use(common.ProtocolMiddlewares()...) r.Use(common.ProtocolMiddlewares()...)
r.Mount("/", web_routers.Routes()) r.Mount("/", web_routers.Routes())

View File

@ -17,12 +17,12 @@ import (
) )
// Routes registers the installation routes // Routes registers the installation routes
func Routes() *web.Route { func Routes() *web.Router {
base := web.NewRoute() base := web.NewRouter()
base.Use(common.ProtocolMiddlewares()...) base.Use(common.ProtocolMiddlewares()...)
base.Methods("GET, HEAD", "/assets/*", public.FileHandlerFunc()) base.Methods("GET, HEAD", "/assets/*", public.FileHandlerFunc())
r := web.NewRoute() r := web.NewRouter()
r.Use(common.Sessioner(), Contexter()) r.Use(common.Sessioner(), Contexter())
r.Get("/", Install) // it must be on the root, because the "install.js" use the window.location to replace the "localhost" AppURL r.Get("/", Install) // it must be on the root, because the "install.js" use the window.location to replace the "localhost" AppURL
r.Post("/", web.Bind(forms.InstallForm{}), SubmitInstall) r.Post("/", web.Bind(forms.InstallForm{}), SubmitInstall)

View File

@ -16,9 +16,9 @@ import (
// SetDefaultBranch updates the default branch // SetDefaultBranch updates the default branch
func SetDefaultBranch(ctx *gitea_context.PrivateContext) { func SetDefaultBranch(ctx *gitea_context.PrivateContext) {
ownerName := ctx.Params(":owner") ownerName := ctx.PathParam(":owner")
repoName := ctx.Params(":repo") repoName := ctx.PathParam(":repo")
branch := ctx.Params(":branch") branch := ctx.PathParam(":branch")
ctx.Repo.Repository.DefaultBranch = branch ctx.Repo.Repository.DefaultBranch = branch
if err := gitrepo.SetDefaultBranch(ctx, ctx.Repo.Repository, ctx.Repo.Repository.DefaultBranch); err != nil { if err := gitrepo.SetDefaultBranch(ctx, ctx.Repo.Repository, ctx.Repo.Repository.DefaultBranch); err != nil {

View File

@ -40,8 +40,8 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
// b) our update function will likely change the repository in the db so we will need to refresh it // b) our update function will likely change the repository in the db so we will need to refresh it
// c) we don't always need the repo // c) we don't always need the repo
ownerName := ctx.Params(":owner") ownerName := ctx.PathParam(":owner")
repoName := ctx.Params(":repo") repoName := ctx.PathParam(":repo")
// defer getting the repository at this point - as we should only retrieve it if we're going to call update // defer getting the repository at this point - as we should only retrieve it if we're going to call update
var ( var (

Some files were not shown because too many files have changed in this diff Show More