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:
@ -36,16 +36,16 @@ func NewFuncMap() template.FuncMap {
|
||||
// -----------------------------------------------------------------
|
||||
// html/template related functions
|
||||
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
|
||||
"Iif": Iif,
|
||||
"Eval": Eval,
|
||||
"SafeHTML": SafeHTML,
|
||||
"Iif": iif,
|
||||
"Eval": evalTokens,
|
||||
"SafeHTML": safeHTML,
|
||||
"HTMLFormat": HTMLFormat,
|
||||
"HTMLEscape": HTMLEscape,
|
||||
"QueryEscape": QueryEscape,
|
||||
"JSEscape": JSEscapeSafe,
|
||||
"HTMLEscape": htmlEscape,
|
||||
"QueryEscape": queryEscape,
|
||||
"JSEscape": jsEscapeSafe,
|
||||
"SanitizeHTML": SanitizeHTML,
|
||||
"URLJoin": util.URLJoin,
|
||||
"DotEscape": DotEscape,
|
||||
"DotEscape": dotEscape,
|
||||
|
||||
"PathEscape": url.PathEscape,
|
||||
"PathEscapeSegments": util.PathEscapeSegments,
|
||||
@ -59,9 +59,9 @@ func NewFuncMap() template.FuncMap {
|
||||
// svg / avatar / icon / color
|
||||
"svg": svg.RenderHTML,
|
||||
"EntryIcon": base.EntryIcon,
|
||||
"MigrationIcon": MigrationIcon,
|
||||
"ActionIcon": ActionIcon,
|
||||
"SortArrow": SortArrow,
|
||||
"MigrationIcon": migrationIcon,
|
||||
"ActionIcon": actionIcon,
|
||||
"SortArrow": sortArrow,
|
||||
"ContrastColor": util.ContrastColor,
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
@ -139,7 +139,7 @@ func NewFuncMap() template.FuncMap {
|
||||
"DisableImportLocal": func() bool {
|
||||
return !setting.ImportLocalPaths
|
||||
},
|
||||
"UserThemeName": UserThemeName,
|
||||
"UserThemeName": userThemeName,
|
||||
"NotificationSettings": func() map[string]any {
|
||||
return map[string]any{
|
||||
"MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
|
||||
@ -155,28 +155,28 @@ func NewFuncMap() template.FuncMap {
|
||||
// -----------------------------------------------------------------
|
||||
// render
|
||||
"RenderCommitMessage": RenderCommitMessage,
|
||||
"RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
|
||||
"RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject,
|
||||
|
||||
"RenderCommitBody": RenderCommitBody,
|
||||
"RenderCodeBlock": RenderCodeBlock,
|
||||
"RenderIssueTitle": RenderIssueTitle,
|
||||
"RenderEmoji": RenderEmoji,
|
||||
"ReactionToEmoji": ReactionToEmoji,
|
||||
"RenderCommitBody": renderCommitBody,
|
||||
"RenderCodeBlock": renderCodeBlock,
|
||||
"RenderIssueTitle": renderIssueTitle,
|
||||
"RenderEmoji": renderEmoji,
|
||||
"ReactionToEmoji": reactionToEmoji,
|
||||
|
||||
"RenderMarkdownToHtml": RenderMarkdownToHtml,
|
||||
"RenderLabel": RenderLabel,
|
||||
"RenderLabel": renderLabel,
|
||||
"RenderLabels": RenderLabels,
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// misc
|
||||
"ShortSha": base.ShortSha,
|
||||
"ActionContent2Commits": ActionContent2Commits,
|
||||
"IsMultilineCommitMessage": IsMultilineCommitMessage,
|
||||
"IsMultilineCommitMessage": isMultilineCommitMessage,
|
||||
"CommentMustAsDiff": gitdiff.CommentMustAsDiff,
|
||||
"MirrorRemoteAddress": mirrorRemoteAddress,
|
||||
|
||||
"FilenameIsImage": FilenameIsImage,
|
||||
"TabSizeClass": TabSizeClass,
|
||||
"FilenameIsImage": filenameIsImage,
|
||||
"TabSizeClass": tabSizeClass,
|
||||
}
|
||||
}
|
||||
|
||||
@ -197,8 +197,8 @@ func HTMLFormat(s string, rawArgs ...any) template.HTML {
|
||||
return template.HTML(fmt.Sprintf(s, args...))
|
||||
}
|
||||
|
||||
// SafeHTML render raw as HTML
|
||||
func SafeHTML(s any) template.HTML {
|
||||
// safeHTML render raw as HTML
|
||||
func safeHTML(s any) template.HTML {
|
||||
switch v := s.(type) {
|
||||
case string:
|
||||
return template.HTML(v)
|
||||
@ -213,7 +213,7 @@ func SanitizeHTML(s string) template.HTML {
|
||||
return template.HTML(markup.Sanitize(s))
|
||||
}
|
||||
|
||||
func HTMLEscape(s any) template.HTML {
|
||||
func htmlEscape(s any) template.HTML {
|
||||
switch v := s.(type) {
|
||||
case string:
|
||||
return template.HTML(html.EscapeString(v))
|
||||
@ -223,22 +223,22 @@ func HTMLEscape(s any) template.HTML {
|
||||
panic(fmt.Sprintf("unexpected type %T", s))
|
||||
}
|
||||
|
||||
func JSEscapeSafe(s string) template.HTML {
|
||||
func jsEscapeSafe(s string) template.HTML {
|
||||
return template.HTML(template.JSEscapeString(s))
|
||||
}
|
||||
|
||||
func QueryEscape(s string) template.URL {
|
||||
func queryEscape(s string) template.URL {
|
||||
return template.URL(url.QueryEscape(s))
|
||||
}
|
||||
|
||||
// DotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent autolinkers from detecting these as urls
|
||||
func DotEscape(raw string) string {
|
||||
// dotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent auto-linkers from detecting these as urls
|
||||
func dotEscape(raw string) string {
|
||||
return strings.ReplaceAll(raw, ".", "\u200d.\u200d")
|
||||
}
|
||||
|
||||
// Iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
|
||||
// and it could be simply used as "{{Iif expr trueVal}}" (omit the falseVal).
|
||||
func Iif(condition any, vals ...any) any {
|
||||
// iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
|
||||
// and it could be simply used as "{{iif expr trueVal}}" (omit the falseVal).
|
||||
func iif(condition any, vals ...any) any {
|
||||
if isTemplateTruthy(condition) {
|
||||
return vals[0]
|
||||
} else if len(vals) > 1 {
|
||||
@ -273,19 +273,19 @@ func isTemplateTruthy(v any) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Eval the expression and return the result, see the comment of eval.Expr for details.
|
||||
// evalTokens evaluates the expression by tokens and returns the result, see the comment of eval.Expr for details.
|
||||
// To use this helper function in templates, pass each token as a separate parameter.
|
||||
//
|
||||
// {{ $int64 := Eval $var "+" 1 }}
|
||||
// {{ $float64 := Eval $var "+" 1.0 }}
|
||||
//
|
||||
// Golang's template supports comparable int types, so the int64 result can be used in later statements like {{if lt $int64 10}}
|
||||
func Eval(tokens ...any) (any, error) {
|
||||
func evalTokens(tokens ...any) (any, error) {
|
||||
n, err := eval.Expr(tokens...)
|
||||
return n.Value, err
|
||||
}
|
||||
|
||||
func UserThemeName(user *user_model.User) string {
|
||||
func userThemeName(user *user_model.User) string {
|
||||
if user == nil || user.Theme == "" {
|
||||
return setting.UI.DefaultTheme
|
||||
}
|
||||
|
@ -58,7 +58,7 @@ func TestSubjectBodySeparator(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestJSEscapeSafe(t *testing.T) {
|
||||
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, JSEscapeSafe(`&<>'"`))
|
||||
assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, jsEscapeSafe(`&<>'"`))
|
||||
}
|
||||
|
||||
func TestHTMLFormat(t *testing.T) {
|
||||
@ -71,7 +71,7 @@ func TestSanitizeHTML(t *testing.T) {
|
||||
|
||||
func TestTemplateTruthy(t *testing.T) {
|
||||
tmpl := template.New("test")
|
||||
tmpl.Funcs(template.FuncMap{"Iif": Iif})
|
||||
tmpl.Funcs(template.FuncMap{"Iif": iif})
|
||||
template.Must(tmpl.Parse(`{{if .Value}}true{{else}}false{{end}}:{{Iif .Value "true" "false"}}`))
|
||||
|
||||
cases := []any{
|
||||
|
@ -22,7 +22,7 @@ var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}\s*$`)
|
||||
func mailSubjectTextFuncMap() texttmpl.FuncMap {
|
||||
return texttmpl.FuncMap{
|
||||
"dict": dict,
|
||||
"Eval": Eval,
|
||||
"Eval": evalTokens,
|
||||
|
||||
"EllipsisString": base.EllipsisString,
|
||||
"AppName": func() string {
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
"github.com/editorconfig/editorconfig-core-go/v2"
|
||||
)
|
||||
|
||||
func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
|
||||
func sortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML {
|
||||
// if needed
|
||||
if len(normSort) == 0 || len(urlSort) == 0 {
|
||||
return ""
|
||||
@ -50,8 +50,8 @@ func SortArrow(normSort, revSort, urlSort string, isDefault bool) template.HTML
|
||||
return ""
|
||||
}
|
||||
|
||||
// IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
|
||||
func IsMultilineCommitMessage(msg string) bool {
|
||||
// isMultilineCommitMessage checks to see if a commit message contains multiple lines.
|
||||
func isMultilineCommitMessage(msg string) bool {
|
||||
return strings.Count(strings.TrimSpace(msg), "\n") >= 1
|
||||
}
|
||||
|
||||
@ -69,8 +69,8 @@ type Actioner interface {
|
||||
GetIssueInfos() []string
|
||||
}
|
||||
|
||||
// ActionIcon accepts an action operation type and returns an icon class name.
|
||||
func ActionIcon(opType activities_model.ActionType) string {
|
||||
// actionIcon accepts an action operation type and returns an icon class name.
|
||||
func actionIcon(opType activities_model.ActionType) string {
|
||||
switch opType {
|
||||
case activities_model.ActionCreateRepo, activities_model.ActionTransferRepo, activities_model.ActionRenameRepo:
|
||||
return "repo"
|
||||
@ -126,8 +126,8 @@ func ActionContent2Commits(act Actioner) *repository.PushCommits {
|
||||
return push
|
||||
}
|
||||
|
||||
// MigrationIcon returns a SVG name matching the service an issue/comment was migrated from
|
||||
func MigrationIcon(hostname string) string {
|
||||
// migrationIcon returns a SVG name matching the service an issue/comment was migrated from
|
||||
func migrationIcon(hostname string) string {
|
||||
switch hostname {
|
||||
case "github.com":
|
||||
return "octicon-mark-github"
|
||||
@ -177,12 +177,12 @@ func mirrorRemoteAddress(ctx context.Context, m *repo_model.Repository, remoteNa
|
||||
return ret
|
||||
}
|
||||
|
||||
func FilenameIsImage(filename string) bool {
|
||||
func filenameIsImage(filename string) bool {
|
||||
mimeType := mime.TypeByExtension(filepath.Ext(filename))
|
||||
return strings.HasPrefix(mimeType, "image/")
|
||||
}
|
||||
|
||||
func TabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
|
||||
func tabSizeClass(ec *editorconfig.Editorconfig, filename string) string {
|
||||
if ec != nil {
|
||||
def, err := ec.GetDefinitionForFilename(filename)
|
||||
if err == nil && def.TabWidth >= 1 && def.TabWidth <= 16 {
|
||||
|
@ -41,12 +41,12 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin
|
||||
if len(msgLines) == 0 {
|
||||
return template.HTML("")
|
||||
}
|
||||
return RenderCodeBlock(template.HTML(msgLines[0]))
|
||||
return renderCodeBlock(template.HTML(msgLines[0]))
|
||||
}
|
||||
|
||||
// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
|
||||
// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to
|
||||
// the provided default url, handling for special links without email to links.
|
||||
func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
|
||||
func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
|
||||
msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
|
||||
lineEnd := strings.IndexByte(msgLine, '\n')
|
||||
if lineEnd > 0 {
|
||||
@ -68,11 +68,11 @@ func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
|
||||
log.Error("RenderCommitMessageSubject: %v", err)
|
||||
return template.HTML("")
|
||||
}
|
||||
return RenderCodeBlock(template.HTML(renderedMessage))
|
||||
return renderCodeBlock(template.HTML(renderedMessage))
|
||||
}
|
||||
|
||||
// RenderCommitBody extracts the body of a commit message without its title.
|
||||
func RenderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
|
||||
// renderCommitBody extracts the body of a commit message without its title.
|
||||
func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
|
||||
msgLine := strings.TrimSpace(msg)
|
||||
lineEnd := strings.IndexByte(msgLine, '\n')
|
||||
if lineEnd > 0 {
|
||||
@ -99,14 +99,14 @@ func RenderCommitBody(ctx context.Context, msg string, metas map[string]string)
|
||||
// Match text that is between back ticks.
|
||||
var codeMatcher = regexp.MustCompile("`([^`]+)`")
|
||||
|
||||
// RenderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
|
||||
func RenderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
|
||||
// renderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
|
||||
func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
|
||||
htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags
|
||||
return template.HTML(htmlWithCodeTags)
|
||||
}
|
||||
|
||||
// RenderIssueTitle renders issue/pull title with defined post processors
|
||||
func RenderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
|
||||
// renderIssueTitle renders issue/pull title with defined post processors
|
||||
func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
|
||||
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
|
||||
Ctx: ctx,
|
||||
Metas: metas,
|
||||
@ -118,9 +118,9 @@ func RenderIssueTitle(ctx context.Context, text string, metas map[string]string)
|
||||
return template.HTML(renderedText)
|
||||
}
|
||||
|
||||
// RenderLabel renders a label
|
||||
// renderLabel renders a label
|
||||
// locale is needed due to an import cycle with our context providing the `Tr` function
|
||||
func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
|
||||
func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
|
||||
var extraCSSClasses string
|
||||
textColor := util.ContrastColor(label.Color)
|
||||
labelScope := label.ExclusiveScope()
|
||||
@ -134,12 +134,12 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
|
||||
if labelScope == "" {
|
||||
// Regular label
|
||||
return HTMLFormat(`<div class="ui label %s" style="color: %s !important; background-color: %s !important;" data-tooltip-content title="%s">%s</div>`,
|
||||
extraCSSClasses, textColor, label.Color, descriptionText, RenderEmoji(ctx, label.Name))
|
||||
extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name))
|
||||
}
|
||||
|
||||
// Scoped label
|
||||
scopeHTML := RenderEmoji(ctx, labelScope)
|
||||
itemHTML := RenderEmoji(ctx, label.Name[len(labelScope)+1:])
|
||||
scopeHTML := renderEmoji(ctx, labelScope)
|
||||
itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])
|
||||
|
||||
// Make scope and item background colors slightly darker and lighter respectively.
|
||||
// More contrast needed with higher luminance, empirically tweaked.
|
||||
@ -176,8 +176,8 @@ func RenderLabel(ctx context.Context, locale translation.Locale, label *issues_m
|
||||
textColor, itemColor, itemHTML)
|
||||
}
|
||||
|
||||
// RenderEmoji renders html text with emoji post processors
|
||||
func RenderEmoji(ctx context.Context, text string) template.HTML {
|
||||
// renderEmoji renders html text with emoji post processors
|
||||
func renderEmoji(ctx context.Context, text string) template.HTML {
|
||||
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
|
||||
template.HTMLEscapeString(text))
|
||||
if err != nil {
|
||||
@ -187,8 +187,8 @@ func RenderEmoji(ctx context.Context, text string) template.HTML {
|
||||
return template.HTML(renderedText)
|
||||
}
|
||||
|
||||
// ReactionToEmoji renders emoji for use in reactions
|
||||
func ReactionToEmoji(reaction string) template.HTML {
|
||||
// reactionToEmoji renders emoji for use in reactions
|
||||
func reactionToEmoji(reaction string) template.HTML {
|
||||
val := emoji.FromCode(reaction)
|
||||
if val != nil {
|
||||
return template.HTML(val.Emoji)
|
||||
@ -220,7 +220,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
|
||||
if label == nil {
|
||||
continue
|
||||
}
|
||||
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, RenderLabel(ctx, locale, label))
|
||||
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, renderLabel(ctx, locale, label))
|
||||
}
|
||||
htmlCode += "</span>"
|
||||
return template.HTML(htmlCode)
|
||||
|
@ -103,7 +103,7 @@ func TestRenderCommitBody(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equalf(t, tt.want, RenderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
|
||||
assert.Equalf(t, tt.want, renderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
|
||||
})
|
||||
}
|
||||
|
||||
@ -127,7 +127,7 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit
|
||||
<a href="/user13/repo11/issues/123" class="ref-issue">#123</a>
|
||||
space`
|
||||
|
||||
assert.EqualValues(t, expected, RenderCommitBody(context.Background(), testInput(), testMetas))
|
||||
assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas))
|
||||
}
|
||||
|
||||
func TestRenderCommitMessage(t *testing.T) {
|
||||
@ -139,7 +139,7 @@ func TestRenderCommitMessage(t *testing.T) {
|
||||
func TestRenderCommitMessageLinkSubject(t *testing.T) {
|
||||
expected := `<a href="https://example.com/link" class="default-link muted">space </a><a href="/mention-user" class="mention">@mention-user</a>`
|
||||
|
||||
assert.EqualValues(t, expected, RenderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
|
||||
assert.EqualValues(t, expected, renderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
|
||||
}
|
||||
|
||||
func TestRenderIssueTitle(t *testing.T) {
|
||||
@ -165,7 +165,7 @@ mail@domain.com
|
||||
space<SPACE><SPACE>
|
||||
`
|
||||
expected = strings.ReplaceAll(expected, "<SPACE>", " ")
|
||||
assert.EqualValues(t, expected, RenderIssueTitle(context.Background(), testInput(), testMetas))
|
||||
assert.EqualValues(t, expected, renderIssueTitle(context.Background(), testInput(), testMetas))
|
||||
}
|
||||
|
||||
func TestRenderMarkdownToHtml(t *testing.T) {
|
||||
|
@ -36,30 +36,30 @@ func GetForm(dataStore middleware.ContextDataStore) any {
|
||||
return dataStore.GetData()["__form"]
|
||||
}
|
||||
|
||||
// Route defines a route based on chi's router
|
||||
type Route struct {
|
||||
R chi.Router
|
||||
// Router defines a route based on chi's router
|
||||
type Router struct {
|
||||
chiRouter chi.Router
|
||||
curGroupPrefix string
|
||||
curMiddlewares []any
|
||||
}
|
||||
|
||||
// NewRoute creates a new route
|
||||
func NewRoute() *Route {
|
||||
// NewRouter creates a new route
|
||||
func NewRouter() *Router {
|
||||
r := chi.NewRouter()
|
||||
return &Route{R: r}
|
||||
return &Router{chiRouter: r}
|
||||
}
|
||||
|
||||
// Use supports two middlewares
|
||||
func (r *Route) Use(middlewares ...any) {
|
||||
func (r *Router) Use(middlewares ...any) {
|
||||
for _, m := range middlewares {
|
||||
if m != nil {
|
||||
r.R.Use(toHandlerProvider(m))
|
||||
r.chiRouter.Use(toHandlerProvider(m))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Group mounts a sub-Router along a `pattern` string.
|
||||
func (r *Route) Group(pattern string, fn func(), middlewares ...any) {
|
||||
func (r *Router) Group(pattern string, fn func(), middlewares ...any) {
|
||||
previousGroupPrefix := r.curGroupPrefix
|
||||
previousMiddlewares := r.curMiddlewares
|
||||
r.curGroupPrefix += pattern
|
||||
@ -71,7 +71,7 @@ func (r *Route) Group(pattern string, fn func(), middlewares ...any) {
|
||||
r.curMiddlewares = previousMiddlewares
|
||||
}
|
||||
|
||||
func (r *Route) getPattern(pattern string) string {
|
||||
func (r *Router) getPattern(pattern string) string {
|
||||
newPattern := r.curGroupPrefix + pattern
|
||||
if !strings.HasPrefix(newPattern, "/") {
|
||||
newPattern = "/" + newPattern
|
||||
@ -82,7 +82,7 @@ func (r *Route) getPattern(pattern string) string {
|
||||
return strings.TrimSuffix(newPattern, "/")
|
||||
}
|
||||
|
||||
func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Handler, http.HandlerFunc) {
|
||||
func (r *Router) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Handler, http.HandlerFunc) {
|
||||
handlerProviders := make([]func(http.Handler) http.Handler, 0, len(r.curMiddlewares)+len(h)+1)
|
||||
for _, m := range r.curMiddlewares {
|
||||
if m != nil {
|
||||
@ -96,7 +96,7 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han
|
||||
}
|
||||
middlewares := handlerProviders[:len(handlerProviders)-1]
|
||||
handlerFunc := handlerProviders[len(handlerProviders)-1](nil).ServeHTTP
|
||||
mockPoint := RouteMockPoint(MockAfterMiddlewares)
|
||||
mockPoint := RouterMockPoint(MockAfterMiddlewares)
|
||||
if mockPoint != nil {
|
||||
middlewares = append(middlewares, mockPoint)
|
||||
}
|
||||
@ -105,72 +105,72 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han
|
||||
|
||||
// Methods adds the same handlers for multiple http "methods" (separated by ",").
|
||||
// If any method is invalid, the lower level router will panic.
|
||||
func (r *Route) Methods(methods, pattern string, h ...any) {
|
||||
func (r *Router) Methods(methods, pattern string, h ...any) {
|
||||
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
|
||||
fullPattern := r.getPattern(pattern)
|
||||
if strings.Contains(methods, ",") {
|
||||
methods := strings.Split(methods, ",")
|
||||
for _, method := range methods {
|
||||
r.R.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
|
||||
r.chiRouter.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
|
||||
}
|
||||
} else {
|
||||
r.R.With(middlewares...).Method(methods, fullPattern, handlerFunc)
|
||||
r.chiRouter.With(middlewares...).Method(methods, fullPattern, handlerFunc)
|
||||
}
|
||||
}
|
||||
|
||||
// Mount attaches another Route along ./pattern/*
|
||||
func (r *Route) Mount(pattern string, subR *Route) {
|
||||
subR.Use(r.curMiddlewares...)
|
||||
r.R.Mount(r.getPattern(pattern), subR.R)
|
||||
// Mount attaches another Router along ./pattern/*
|
||||
func (r *Router) Mount(pattern string, subRouter *Router) {
|
||||
subRouter.Use(r.curMiddlewares...)
|
||||
r.chiRouter.Mount(r.getPattern(pattern), subRouter.chiRouter)
|
||||
}
|
||||
|
||||
// Any delegate requests for all methods
|
||||
func (r *Route) Any(pattern string, h ...any) {
|
||||
func (r *Router) Any(pattern string, h ...any) {
|
||||
middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h)
|
||||
r.R.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc)
|
||||
r.chiRouter.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc)
|
||||
}
|
||||
|
||||
// Delete delegate delete method
|
||||
func (r *Route) Delete(pattern string, h ...any) {
|
||||
func (r *Router) Delete(pattern string, h ...any) {
|
||||
r.Methods("DELETE", pattern, h...)
|
||||
}
|
||||
|
||||
// Get delegate get method
|
||||
func (r *Route) Get(pattern string, h ...any) {
|
||||
func (r *Router) Get(pattern string, h ...any) {
|
||||
r.Methods("GET", pattern, h...)
|
||||
}
|
||||
|
||||
// Head delegate head method
|
||||
func (r *Route) Head(pattern string, h ...any) {
|
||||
func (r *Router) Head(pattern string, h ...any) {
|
||||
r.Methods("HEAD", pattern, h...)
|
||||
}
|
||||
|
||||
// Post delegate post method
|
||||
func (r *Route) Post(pattern string, h ...any) {
|
||||
func (r *Router) Post(pattern string, h ...any) {
|
||||
r.Methods("POST", pattern, h...)
|
||||
}
|
||||
|
||||
// Put delegate put method
|
||||
func (r *Route) Put(pattern string, h ...any) {
|
||||
func (r *Router) Put(pattern string, h ...any) {
|
||||
r.Methods("PUT", pattern, h...)
|
||||
}
|
||||
|
||||
// Patch delegate patch method
|
||||
func (r *Route) Patch(pattern string, h ...any) {
|
||||
func (r *Router) Patch(pattern string, h ...any) {
|
||||
r.Methods("PATCH", pattern, h...)
|
||||
}
|
||||
|
||||
// ServeHTTP implements http.Handler
|
||||
func (r *Route) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
r.normalizeRequestPath(w, req, r.R)
|
||||
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
r.normalizeRequestPath(w, req, r.chiRouter)
|
||||
}
|
||||
|
||||
// NotFound defines a handler to respond whenever a route could not be found.
|
||||
func (r *Route) NotFound(h http.HandlerFunc) {
|
||||
r.R.NotFound(h)
|
||||
func (r *Router) NotFound(h http.HandlerFunc) {
|
||||
r.chiRouter.NotFound(h)
|
||||
}
|
||||
|
||||
func (r *Route) normalizeRequestPath(resp http.ResponseWriter, req *http.Request, next http.Handler) {
|
||||
func (r *Router) normalizeRequestPath(resp http.ResponseWriter, req *http.Request, next http.Handler) {
|
||||
normalized := false
|
||||
normalizedPath := req.URL.EscapedPath()
|
||||
if normalizedPath == "" {
|
||||
@ -226,13 +226,13 @@ func (r *Route) normalizeRequestPath(resp http.ResponseWriter, req *http.Request
|
||||
}
|
||||
|
||||
// Combo delegates requests to Combo
|
||||
func (r *Route) Combo(pattern string, h ...any) *Combo {
|
||||
func (r *Router) Combo(pattern string, h ...any) *Combo {
|
||||
return &Combo{r, pattern, h}
|
||||
}
|
||||
|
||||
// Combo represents a tiny group routes with same pattern
|
||||
type Combo struct {
|
||||
r *Route
|
||||
r *Router
|
||||
pattern string
|
||||
h []any
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ func TestRoute1(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
recorder.Body = buff
|
||||
|
||||
r := NewRoute()
|
||||
r := NewRouter()
|
||||
r.Get("/{username}/{reponame}/{type:issues|pulls}", func(resp http.ResponseWriter, req *http.Request) {
|
||||
username := chi.URLParam(req, "username")
|
||||
assert.EqualValues(t, "gitea", username)
|
||||
@ -45,7 +45,7 @@ func TestRoute2(t *testing.T) {
|
||||
|
||||
hit := -1
|
||||
|
||||
r := NewRoute()
|
||||
r := NewRouter()
|
||||
r.Group("/{username}/{reponame}", func() {
|
||||
r.Group("", func() {
|
||||
r.Get("/{type:issues|pulls}", func(resp http.ResponseWriter, req *http.Request) {
|
||||
@ -121,8 +121,8 @@ func TestRoute3(t *testing.T) {
|
||||
|
||||
hit := -1
|
||||
|
||||
m := NewRoute()
|
||||
r := NewRoute()
|
||||
m := NewRouter()
|
||||
r := NewRouter()
|
||||
r.Mount("/api/v1", m)
|
||||
|
||||
m.Group("/repos", func() {
|
||||
@ -189,7 +189,7 @@ func TestRouteNormalizePath(t *testing.T) {
|
||||
recorder.Body = bytes.NewBuffer(nil)
|
||||
|
||||
actualPaths := paths{EscapedPath: "(none)", RawPath: "(none)", Path: "(none)"}
|
||||
r := NewRoute()
|
||||
r := NewRouter()
|
||||
r.Get("/*", func(resp http.ResponseWriter, req *http.Request) {
|
||||
actualPaths.EscapedPath = req.URL.EscapedPath()
|
||||
actualPaths.RawPath = req.URL.RawPath
|
||||
|
@ -14,14 +14,14 @@ const MockAfterMiddlewares = "MockAfterMiddlewares"
|
||||
|
||||
var routeMockPoints = map[string]func(next http.Handler) http.Handler{}
|
||||
|
||||
// RouteMockPoint registers a mock point as a middleware for testing, example:
|
||||
// RouterMockPoint registers a mock point as a middleware for testing, example:
|
||||
//
|
||||
// r.Use(web.RouteMockPoint("my-mock-point-1"))
|
||||
// r.Get("/foo", middleware2, web.RouteMockPoint("my-mock-point-2"), middleware2, handler)
|
||||
// r.Use(web.RouterMockPoint("my-mock-point-1"))
|
||||
// r.Get("/foo", middleware2, web.RouterMockPoint("my-mock-point-2"), middleware2, handler)
|
||||
//
|
||||
// Then use web.RouteMock to mock the route execution.
|
||||
// It only takes effect in testing mode (setting.IsInTesting == true).
|
||||
func RouteMockPoint(pointName string) func(next http.Handler) http.Handler {
|
||||
func RouterMockPoint(pointName string) func(next http.Handler) http.Handler {
|
||||
if !setting.IsInTesting {
|
||||
return nil
|
||||
}
|
||||
|
@ -16,7 +16,7 @@ import (
|
||||
func TestRouteMock(t *testing.T) {
|
||||
setting.IsInTesting = true
|
||||
|
||||
r := NewRoute()
|
||||
r := NewRouter()
|
||||
middleware1 := func(resp http.ResponseWriter, req *http.Request) {
|
||||
resp.Header().Set("X-Test-Middleware1", "m1")
|
||||
}
|
||||
@ -26,7 +26,7 @@ func TestRouteMock(t *testing.T) {
|
||||
handler := func(resp http.ResponseWriter, req *http.Request) {
|
||||
resp.Header().Set("X-Test-Handler", "h")
|
||||
}
|
||||
r.Get("/foo", middleware1, RouteMockPoint("mock-point"), middleware2, handler)
|
||||
r.Get("/foo", middleware1, RouterMockPoint("mock-point"), middleware2, handler)
|
||||
|
||||
// normal request
|
||||
recorder := httptest.NewRecorder()
|
||||
|
@ -11,8 +11,8 @@ import (
|
||||
"code.gitea.io/gitea/routers/api/actions/runner"
|
||||
)
|
||||
|
||||
func Routes(prefix string) *web.Route {
|
||||
m := web.NewRoute()
|
||||
func Routes(prefix string) *web.Router {
|
||||
m := web.NewRouter()
|
||||
|
||||
path, handler := ping.NewPingServiceHandler()
|
||||
m.Post(path+"*", http.StripPrefix(prefix, handler).ServeHTTP)
|
||||
|
@ -101,8 +101,8 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
func ArtifactsRoutes(prefix string) *web.Route {
|
||||
m := web.NewRoute()
|
||||
func ArtifactsRoutes(prefix string) *web.Router {
|
||||
m := web.NewRouter()
|
||||
m.Use(ArtifactContexter())
|
||||
|
||||
r := artifactRoutes{
|
||||
@ -457,7 +457,7 @@ func (ar artifactRoutes) downloadArtifact(ctx *ArtifactContext) {
|
||||
return
|
||||
}
|
||||
|
||||
artifactID := ctx.ParamsInt64("artifact_id")
|
||||
artifactID := ctx.PathParamInt64("artifact_id")
|
||||
artifact, exist, err := db.GetByID[actions.ActionArtifact](ctx, artifactID)
|
||||
if err != nil {
|
||||
log.Error("Error getting artifact: %v", err)
|
||||
|
@ -34,7 +34,7 @@ func validateArtifactName(ctx *ArtifactContext, artifactName string) bool {
|
||||
|
||||
func validateRunID(ctx *ArtifactContext) (*actions.ActionTask, int64, bool) {
|
||||
task := ctx.ActionTask
|
||||
runID := ctx.ParamsInt64("run_id")
|
||||
runID := ctx.PathParamInt64("run_id")
|
||||
if task.Job.RunID != runID {
|
||||
log.Error("Error runID 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 {
|
||||
paramHash := ctx.Params("artifact_hash")
|
||||
paramHash := ctx.PathParam("artifact_hash")
|
||||
// use artifact name to create upload url
|
||||
artifactHash := fmt.Sprintf("%x", md5.Sum([]byte(artifactName)))
|
||||
if paramHash == artifactHash {
|
||||
|
@ -129,8 +129,8 @@ func ArtifactV4Contexter() func(next http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
func ArtifactsV4Routes(prefix string) *web.Route {
|
||||
m := web.NewRoute()
|
||||
func ArtifactsV4Routes(prefix string) *web.Router {
|
||||
m := web.NewRouter()
|
||||
|
||||
r := artifactV4Routes{
|
||||
prefix: prefix,
|
||||
|
@ -73,7 +73,7 @@ func GetRepositoryFile(ctx *context.Context) {
|
||||
pv,
|
||||
&packages_service.PackageFileInfo{
|
||||
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 {
|
||||
@ -89,8 +89,8 @@ func GetRepositoryFile(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func UploadPackageFile(ctx *context.Context) {
|
||||
branch := strings.TrimSpace(ctx.Params("branch"))
|
||||
repository := strings.TrimSpace(ctx.Params("repository"))
|
||||
branch := strings.TrimSpace(ctx.PathParam("branch"))
|
||||
repository := strings.TrimSpace(ctx.PathParam("repository"))
|
||||
if branch == "" || repository == "" {
|
||||
apiError(ctx, http.StatusBadRequest, "invalid branch or repository")
|
||||
return
|
||||
@ -182,14 +182,14 @@ func UploadPackageFile(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
branch := ctx.Params("branch")
|
||||
repository := ctx.Params("repository")
|
||||
architecture := ctx.Params("architecture")
|
||||
branch := ctx.PathParam("branch")
|
||||
repository := ctx.PathParam("repository")
|
||||
architecture := ctx.PathParam("architecture")
|
||||
|
||||
opts := &packages_model.PackageFileSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
PackageType: packages_model.TypeAlpine,
|
||||
Query: ctx.Params("filename"),
|
||||
Query: ctx.PathParam("filename"),
|
||||
CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture),
|
||||
}
|
||||
pfs, _, err := packages_model.SearchFiles(ctx, opts)
|
||||
@ -230,12 +230,12 @@ func DownloadPackageFile(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{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
PackageType: packages_model.TypeAlpine,
|
||||
Query: ctx.Params("filename"),
|
||||
Query: ctx.PathParam("filename"),
|
||||
CompositeKey: fmt.Sprintf("%s|%s|%s", branch, repository, architecture),
|
||||
})
|
||||
if err != nil {
|
||||
|
@ -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 {
|
||||
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)
|
||||
// These are mounted on `/api/packages` (not `/api/v1/packages`)
|
||||
func CommonRoutes() *web.Route {
|
||||
r := web.NewRoute()
|
||||
func CommonRoutes() *web.Router {
|
||||
r := web.NewRouter()
|
||||
|
||||
r.Use(context.PackageContexter())
|
||||
|
||||
@ -264,15 +264,15 @@ func CommonRoutes() *web.Route {
|
||||
)
|
||||
|
||||
r.Get("/*", func(ctx *context.Context) {
|
||||
m := downloadPattern.FindStringSubmatch(ctx.Params("*"))
|
||||
m := downloadPattern.FindStringSubmatch(ctx.PathParam("*"))
|
||||
if len(m) == 0 {
|
||||
ctx.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("channel", strings.TrimSuffix(m[1], "/"))
|
||||
ctx.SetParams("architecture", m[2])
|
||||
ctx.SetParams("filename", m[3])
|
||||
ctx.SetPathParam("channel", strings.TrimSuffix(m[1], "/"))
|
||||
ctx.SetPathParam("architecture", m[2])
|
||||
ctx.SetPathParam("filename", m[3])
|
||||
|
||||
switch m[3] {
|
||||
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) {
|
||||
m := uploadPattern.FindStringSubmatch(ctx.Params("*"))
|
||||
m := uploadPattern.FindStringSubmatch(ctx.PathParam("*"))
|
||||
if len(m) == 0 {
|
||||
ctx.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("channel", strings.TrimSuffix(m[1], "/"))
|
||||
ctx.SetParams("filename", m[2])
|
||||
ctx.SetPathParam("channel", strings.TrimSuffix(m[1], "/"))
|
||||
ctx.SetPathParam("filename", m[2])
|
||||
|
||||
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
|
||||
// https://go.dev/ref/mod#goproxy-protocol
|
||||
r.Get("/*", func(ctx *context.Context) {
|
||||
path := ctx.Params("*")
|
||||
path := ctx.PathParam("*")
|
||||
|
||||
if strings.HasSuffix(path, "/@latest") {
|
||||
ctx.SetParams("name", path[:len(path)-len("/@latest")])
|
||||
ctx.SetParams("version", "latest")
|
||||
ctx.SetPathParam("name", path[:len(path)-len("/@latest")])
|
||||
ctx.SetPathParam("version", "latest")
|
||||
|
||||
goproxy.PackageVersionMetadata(ctx)
|
||||
return
|
||||
@ -355,7 +355,7 @@ func CommonRoutes() *web.Route {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("name", parts[0])
|
||||
ctx.SetPathParam("name", parts[0])
|
||||
|
||||
// <package/name>/@v/list
|
||||
if parts[1] == "list" {
|
||||
@ -365,21 +365,21 @@ func CommonRoutes() *web.Route {
|
||||
|
||||
// <package/name>/@v/<version>.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)
|
||||
return
|
||||
}
|
||||
// <package/name>/@v/<version>.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)
|
||||
return
|
||||
}
|
||||
// <package/name>/@v/<version>.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)
|
||||
return
|
||||
@ -525,7 +525,7 @@ func CommonRoutes() *web.Route {
|
||||
)
|
||||
|
||||
r.Methods("HEAD,GET,PUT,DELETE", "*", func(ctx *context.Context) {
|
||||
path := ctx.Params("*")
|
||||
path := ctx.PathParam("*")
|
||||
isHead := ctx.Req.Method == "HEAD"
|
||||
isGetHead := ctx.Req.Method == "HEAD" || ctx.Req.Method == "GET"
|
||||
isPut := ctx.Req.Method == "PUT"
|
||||
@ -533,15 +533,15 @@ func CommonRoutes() *web.Route {
|
||||
|
||||
m := repoPattern.FindStringSubmatch(path)
|
||||
if len(m) == 2 && isGetHead {
|
||||
ctx.SetParams("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetPathParam("group", strings.Trim(m[1], "/"))
|
||||
rpm.GetRepositoryConfig(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
m = repoFilePattern.FindStringSubmatch(path)
|
||||
if len(m) == 3 && isGetHead {
|
||||
ctx.SetParams("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetParams("filename", m[2])
|
||||
ctx.SetPathParam("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetPathParam("filename", m[2])
|
||||
if isHead {
|
||||
rpm.CheckRepositoryFileExistence(ctx)
|
||||
} else {
|
||||
@ -556,17 +556,17 @@ func CommonRoutes() *web.Route {
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.SetParams("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetPathParam("group", strings.Trim(m[1], "/"))
|
||||
rpm.UploadPackageFile(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
m = filePattern.FindStringSubmatch(path)
|
||||
if len(m) == 6 && (isGetHead || isDelete) {
|
||||
ctx.SetParams("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetParams("name", m[2])
|
||||
ctx.SetParams("version", m[3])
|
||||
ctx.SetParams("architecture", m[4])
|
||||
ctx.SetPathParam("group", strings.Trim(m[1], "/"))
|
||||
ctx.SetPathParam("name", m[2])
|
||||
ctx.SetPathParam("version", m[3])
|
||||
ctx.SetPathParam("architecture", m[4])
|
||||
if isGetHead {
|
||||
rpm.DownloadPackageFile(ctx)
|
||||
} else {
|
||||
@ -607,13 +607,13 @@ func CommonRoutes() *web.Route {
|
||||
r.Get("", func(ctx *context.Context) {
|
||||
// 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") {
|
||||
swift.CheckAcceptMediaType(swift.AcceptZip)(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.SetParams("version", version[:len(version)-4])
|
||||
ctx.SetPathParam("version", version[:len(version)-4])
|
||||
swift.DownloadPackageFile(ctx)
|
||||
} else {
|
||||
swift.CheckAcceptMediaType(swift.AcceptJSON)(ctx)
|
||||
@ -621,7 +621,7 @@ func CommonRoutes() *web.Route {
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(version, ".json") {
|
||||
ctx.SetParams("version", version[:len(version)-5])
|
||||
ctx.SetPathParam("version", version[:len(version)-5])
|
||||
}
|
||||
swift.PackageVersionMetadata(ctx)
|
||||
}
|
||||
@ -651,8 +651,8 @@ func CommonRoutes() *web.Route {
|
||||
// ContainerRoutes provides endpoints that implement the OCI API to serve containers
|
||||
// These have to be mounted on `/v2/...` to comply with the OCI spec:
|
||||
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md
|
||||
func ContainerRoutes() *web.Route {
|
||||
r := web.NewRoute()
|
||||
func ContainerRoutes() *web.Router {
|
||||
r := web.NewRouter()
|
||||
|
||||
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
|
||||
r.Methods("HEAD,GET,POST,PUT,PATCH,DELETE", "/*", func(ctx *context.Context) {
|
||||
path := ctx.Params("*")
|
||||
path := ctx.PathParam("*")
|
||||
isHead := ctx.Req.Method == "HEAD"
|
||||
isGet := ctx.Req.Method == "GET"
|
||||
isPost := ctx.Req.Method == "POST"
|
||||
@ -714,7 +714,7 @@ func ContainerRoutes() *web.Route {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("image", path[:len(path)-14])
|
||||
ctx.SetPathParam("image", path[:len(path)-14])
|
||||
container.VerifyImageName(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
@ -724,7 +724,7 @@ func ContainerRoutes() *web.Route {
|
||||
return
|
||||
}
|
||||
if isGet && strings.HasSuffix(path, "/tags/list") {
|
||||
ctx.SetParams("image", path[:len(path)-10])
|
||||
ctx.SetPathParam("image", path[:len(path)-10])
|
||||
container.VerifyImageName(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
@ -741,13 +741,13 @@ func ContainerRoutes() *web.Route {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("image", m[1])
|
||||
ctx.SetPathParam("image", m[1])
|
||||
container.VerifyImageName(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("uuid", m[2])
|
||||
ctx.SetPathParam("uuid", m[2])
|
||||
|
||||
if isGet {
|
||||
container.GetUploadBlob(ctx)
|
||||
@ -762,13 +762,13 @@ func ContainerRoutes() *web.Route {
|
||||
}
|
||||
m = blobsPattern.FindStringSubmatch(path)
|
||||
if len(m) == 3 && (isHead || isGet || isDelete) {
|
||||
ctx.SetParams("image", m[1])
|
||||
ctx.SetPathParam("image", m[1])
|
||||
container.VerifyImageName(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("digest", m[2])
|
||||
ctx.SetPathParam("digest", m[2])
|
||||
|
||||
if isHead {
|
||||
container.HeadBlob(ctx)
|
||||
@ -785,13 +785,13 @@ func ContainerRoutes() *web.Route {
|
||||
}
|
||||
m = manifestsPattern.FindStringSubmatch(path)
|
||||
if len(m) == 3 && (isHead || isGet || isPut || isDelete) {
|
||||
ctx.SetParams("image", m[1])
|
||||
ctx.SetPathParam("image", m[1])
|
||||
container.VerifyImageName(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetParams("reference", m[2])
|
||||
ctx.SetPathParam("reference", m[2])
|
||||
|
||||
if isHead {
|
||||
container.HeadManifest(ctx)
|
||||
|
@ -55,7 +55,7 @@ func RepositoryConfig(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 errors.Is(err, util.ErrNotExist) {
|
||||
apiError(ctx, http.StatusNotFound, err)
|
||||
@ -173,11 +173,11 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
&packages_service.PackageInfo{
|
||||
Owner: ctx.Package.Owner,
|
||||
PackageType: packages_model.TypeCargo,
|
||||
Name: ctx.Params("package"),
|
||||
Version: ctx.Params("version"),
|
||||
Name: ctx.PathParam("package"),
|
||||
Version: ctx.PathParam("version"),
|
||||
},
|
||||
&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 {
|
||||
@ -274,7 +274,7 @@ func UnyankPackage(ctx *context.Context) {
|
||||
}
|
||||
|
||||
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 == packages_model.ErrPackageNotExist {
|
||||
apiError(ctx, http.StatusNotFound, err)
|
||||
|
@ -150,7 +150,7 @@ func EnumeratePackages(ctx *context.Context) {
|
||||
|
||||
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_show.rb
|
||||
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)
|
||||
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
|
||||
func PackageVersionMetadata(ctx *context.Context) {
|
||||
packageName := ctx.Params("name")
|
||||
packageVersion := strings.ReplaceAll(ctx.Params("version"), "_", ".") // Chef calls this endpoint with "_" instead of "."?!
|
||||
packageName := ctx.PathParam("name")
|
||||
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)
|
||||
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
|
||||
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 == packages_model.ErrPackageNotExist {
|
||||
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
|
||||
func DeletePackageVersion(ctx *context.Context) {
|
||||
packageName := ctx.Params("name")
|
||||
packageVersion := ctx.Params("version")
|
||||
packageName := ctx.PathParam("name")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
|
||||
err := packages_service.RemovePackageVersionByNameAndVersion(
|
||||
ctx,
|
||||
@ -381,7 +381,7 @@ func DeletePackageVersion(ctx *context.Context) {
|
||||
|
||||
// https://github.com/chef/chef/blob/main/knife/lib/chef/knife/supermarket_unshare.rb
|
||||
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 {
|
||||
apiError(ctx, http.StatusInternalServerError, err)
|
||||
return
|
||||
|
@ -134,8 +134,8 @@ func EnumeratePackages(ctx *context.Context) {
|
||||
// PackageMetadata returns the metadata for a single package
|
||||
// https://packagist.org/apidoc#get-package-data
|
||||
func PackageMetadata(ctx *context.Context) {
|
||||
vendorName := ctx.Params("vendorname")
|
||||
projectName := ctx.Params("projectname")
|
||||
vendorName := ctx.PathParam("vendorname")
|
||||
projectName := ctx.PathParam("projectname")
|
||||
|
||||
pvs, err := packages_model.GetVersionsByPackageName(ctx, ctx.Package.Owner.ID, packages_model.TypeComposer, vendorName+"/"+projectName)
|
||||
if err != nil {
|
||||
@ -168,11 +168,11 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
&packages_service.PackageInfo{
|
||||
Owner: ctx.Package.Owner,
|
||||
PackageType: packages_model.TypeComposer,
|
||||
Name: ctx.Params("package"),
|
||||
Version: ctx.Params("version"),
|
||||
Name: ctx.PathParam("package"),
|
||||
Version: ctx.PathParam("version"),
|
||||
},
|
||||
&packages_service.PackageFileInfo{
|
||||
Filename: ctx.Params("filename"),
|
||||
Filename: ctx.PathParam("filename"),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
|
@ -72,11 +72,11 @@ func baseURL(ctx *context.Context) string {
|
||||
// ExtractPathParameters is a middleware to extract common parameters from path
|
||||
func ExtractPathParameters(ctx *context.Context) {
|
||||
rref, err := conan_module.NewRecipeReference(
|
||||
ctx.Params("name"),
|
||||
ctx.Params("version"),
|
||||
ctx.Params("user"),
|
||||
ctx.Params("channel"),
|
||||
ctx.Params("recipe_revision"),
|
||||
ctx.PathParam("name"),
|
||||
ctx.PathParam("version"),
|
||||
ctx.PathParam("user"),
|
||||
ctx.PathParam("channel"),
|
||||
ctx.PathParam("recipe_revision"),
|
||||
)
|
||||
if err != nil {
|
||||
apiError(ctx, http.StatusBadRequest, err)
|
||||
@ -85,14 +85,14 @@ func ExtractPathParameters(ctx *context.Context) {
|
||||
|
||||
ctx.Data[recipeReferenceKey] = rref
|
||||
|
||||
reference := ctx.Params("package_reference")
|
||||
reference := ctx.PathParam("package_reference")
|
||||
|
||||
var pref *conan_module.PackageReference
|
||||
if reference != "" {
|
||||
pref, err = conan_module.NewPackageReference(
|
||||
rref,
|
||||
reference,
|
||||
ctx.Params("package_revision"),
|
||||
ctx.PathParam("package_revision"),
|
||||
)
|
||||
if err != nil {
|
||||
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)
|
||||
pref := ctx.Data[packageReferenceKey].(*conan_module.PackageReference)
|
||||
|
||||
filename := ctx.Params("filename")
|
||||
filename := ctx.PathParam("filename")
|
||||
if !fileFilter.Contains(filename) {
|
||||
apiError(ctx, http.StatusBadRequest, nil)
|
||||
return
|
||||
@ -444,7 +444,7 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
func downloadFile(ctx *context.Context, fileFilter container.Set[string], fileKey string) {
|
||||
rref := ctx.Data[recipeReferenceKey].(*conan_module.RecipeReference)
|
||||
|
||||
filename := ctx.Params("filename")
|
||||
filename := ctx.PathParam("filename")
|
||||
if !fileFilter.Contains(filename) {
|
||||
apiError(ctx, http.StatusBadRequest, nil)
|
||||
return
|
||||
|
@ -66,7 +66,7 @@ func EnumeratePackages(ctx *context.Context) {
|
||||
|
||||
repoData := &RepoData{
|
||||
Info: Info{
|
||||
Subdir: ctx.Params("architecture"),
|
||||
Subdir: ctx.PathParam("architecture"),
|
||||
},
|
||||
Packages: 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{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Channel: ctx.Params("channel"),
|
||||
Channel: ctx.PathParam("channel"),
|
||||
Subdir: repoData.Info.Subdir,
|
||||
})
|
||||
if err != nil {
|
||||
@ -151,7 +151,7 @@ func EnumeratePackages(ctx *context.Context) {
|
||||
|
||||
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")
|
||||
} else {
|
||||
resp.Header().Set("Content-Type", "application/x-bzip2")
|
||||
@ -191,7 +191,7 @@ func UploadPackageFile(ctx *context.Context) {
|
||||
defer buf.Close()
|
||||
|
||||
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)
|
||||
} else {
|
||||
pck, err = conda_module.ParsePackageConda(buf, buf.Size())
|
||||
@ -212,7 +212,7 @@ func UploadPackageFile(ctx *context.Context) {
|
||||
|
||||
fullName := pck.Name
|
||||
|
||||
channel := ctx.Params("channel")
|
||||
channel := ctx.PathParam("channel")
|
||||
if channel != "" {
|
||||
fullName = channel + "/" + pck.Name
|
||||
}
|
||||
@ -277,9 +277,9 @@ func UploadPackageFile(ctx *context.Context) {
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
pfs, err := conda_model.SearchFiles(ctx, &conda_model.FileSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Channel: ctx.Params("channel"),
|
||||
Subdir: ctx.Params("architecture"),
|
||||
Filename: ctx.Params("filename"),
|
||||
Channel: ctx.PathParam("channel"),
|
||||
Subdir: ctx.PathParam("architecture"),
|
||||
Filename: ctx.PathParam("filename"),
|
||||
})
|
||||
if err != nil {
|
||||
apiError(ctx, http.StatusInternalServerError, err)
|
||||
|
@ -131,7 +131,7 @@ func ReqContainerAccess(ctx *context.Context) {
|
||||
|
||||
// VerifyImageName is a middleware which checks if the image name is allowed
|
||||
func VerifyImageName(ctx *context.Context) {
|
||||
if !imageNamePattern.MatchString(ctx.Params("image")) {
|
||||
if !imageNamePattern.MatchString(ctx.PathParam("image")) {
|
||||
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#pushing-a-blob-in-chunks
|
||||
func InitiateUploadBlob(ctx *context.Context) {
|
||||
image := ctx.Params("image")
|
||||
image := ctx.PathParam("image")
|
||||
|
||||
mount := ctx.FormTrim("mount")
|
||||
from := ctx.FormTrim("from")
|
||||
@ -305,7 +305,7 @@ func InitiateUploadBlob(ctx *context.Context) {
|
||||
|
||||
// https://docs.docker.com/registry/spec/api/#get-blob-upload
|
||||
func GetUploadBlob(ctx *context.Context) {
|
||||
uuid := ctx.Params("uuid")
|
||||
uuid := ctx.PathParam("uuid")
|
||||
|
||||
upload, err := packages_model.GetBlobUploadByID(ctx, uuid)
|
||||
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
|
||||
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 == packages_model.ErrPackageBlobUploadNotExist {
|
||||
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
|
||||
func EndUploadBlob(ctx *context.Context) {
|
||||
image := ctx.Params("image")
|
||||
image := ctx.PathParam("image")
|
||||
|
||||
digest := ctx.FormTrim("digest")
|
||||
if digest == "" {
|
||||
@ -379,7 +379,7 @@ func EndUploadBlob(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
uploader, err := container_service.NewBlobUploader(ctx, ctx.Params("uuid"))
|
||||
uploader, err := container_service.NewBlobUploader(ctx, ctx.PathParam("uuid"))
|
||||
if err != nil {
|
||||
if err == packages_model.ErrPackageBlobUploadNotExist {
|
||||
apiErrorDefined(ctx, errBlobUploadUnknown)
|
||||
@ -446,7 +446,7 @@ func EndUploadBlob(ctx *context.Context) {
|
||||
|
||||
// https://docs.docker.com/registry/spec/api/#delete-blob-upload
|
||||
func CancelUploadBlob(ctx *context.Context) {
|
||||
uuid := ctx.Params("uuid")
|
||||
uuid := ctx.PathParam("uuid")
|
||||
|
||||
_, err := packages_model.GetBlobUploadByID(ctx, uuid)
|
||||
if err != nil {
|
||||
@ -469,7 +469,7 @@ func CancelUploadBlob(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescriptor, error) {
|
||||
d := ctx.Params("digest")
|
||||
d := ctx.PathParam("digest")
|
||||
|
||||
if digest.Digest(d).Validate() != nil {
|
||||
return nil, container_model.ErrContainerBlobNotExist
|
||||
@ -477,7 +477,7 @@ func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescri
|
||||
|
||||
return workaroundGetContainerBlob(ctx, &container_model.BlobSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Image: ctx.Params("image"),
|
||||
Image: ctx.PathParam("image"),
|
||||
Digest: d,
|
||||
})
|
||||
}
|
||||
@ -518,14 +518,14 @@ func GetBlob(ctx *context.Context) {
|
||||
|
||||
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#deleting-blobs
|
||||
func DeleteBlob(ctx *context.Context) {
|
||||
d := ctx.Params("digest")
|
||||
d := ctx.PathParam("digest")
|
||||
|
||||
if digest.Digest(d).Validate() != nil {
|
||||
apiErrorDefined(ctx, errBlobUnknown)
|
||||
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)
|
||||
return
|
||||
}
|
||||
@ -537,13 +537,13 @@ func DeleteBlob(ctx *context.Context) {
|
||||
|
||||
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests
|
||||
func UploadManifest(ctx *context.Context) {
|
||||
reference := ctx.Params("reference")
|
||||
reference := ctx.PathParam("reference")
|
||||
|
||||
mci := &manifestCreationInfo{
|
||||
MediaType: ctx.Req.Header.Get("Content-Type"),
|
||||
Owner: ctx.Package.Owner,
|
||||
Creator: ctx.Doer,
|
||||
Image: ctx.Params("image"),
|
||||
Image: ctx.PathParam("image"),
|
||||
Reference: reference,
|
||||
IsTagged: digest.Digest(reference).Validate() != nil,
|
||||
}
|
||||
@ -592,11 +592,11 @@ func UploadManifest(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func getBlobSearchOptionsFromContext(ctx *context.Context) (*container_model.BlobSearchOptions, error) {
|
||||
reference := ctx.Params("reference")
|
||||
reference := ctx.PathParam("reference")
|
||||
|
||||
opts := &container_model.BlobSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Image: ctx.Params("image"),
|
||||
Image: ctx.PathParam("image"),
|
||||
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
|
||||
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.ErrPackageNotExist {
|
||||
|
@ -28,18 +28,18 @@ func apiError(ctx *context.Context, status int, obj any) {
|
||||
}
|
||||
|
||||
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,
|
||||
FileType: cran_module.TypeSource,
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
FileType: cran_module.TypeBinary,
|
||||
Platform: ctx.Params("platform"),
|
||||
RVersion: ctx.Params("rversion"),
|
||||
Platform: ctx.PathParam("platform"),
|
||||
RVersion: ctx.PathParam("rversion"),
|
||||
})
|
||||
}
|
||||
|
||||
@ -225,7 +225,7 @@ func DownloadSourcePackageFile(ctx *context.Context) {
|
||||
downloadPackageFile(ctx, &cran_model.SearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
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{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
FileType: cran_module.TypeBinary,
|
||||
Platform: ctx.Params("platform"),
|
||||
RVersion: ctx.Params("rversion"),
|
||||
Filename: ctx.Params("filename"),
|
||||
Platform: ctx.PathParam("platform"),
|
||||
RVersion: ctx.PathParam("rversion"),
|
||||
Filename: ctx.PathParam("filename"),
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -51,10 +51,10 @@ func GetRepositoryFile(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
key := ctx.Params("distribution")
|
||||
key := ctx.PathParam("distribution")
|
||||
|
||||
component := ctx.Params("component")
|
||||
architecture := strings.TrimPrefix(ctx.Params("architecture"), "binary-")
|
||||
component := ctx.PathParam("component")
|
||||
architecture := strings.TrimPrefix(ctx.PathParam("architecture"), "binary-")
|
||||
if component != "" && architecture != "" {
|
||||
key += "|" + component + "|" + architecture
|
||||
}
|
||||
@ -63,7 +63,7 @@ func GetRepositoryFile(ctx *context.Context) {
|
||||
ctx,
|
||||
pv,
|
||||
&packages_service.PackageFileInfo{
|
||||
Filename: ctx.Params("filename"),
|
||||
Filename: ctx.PathParam("filename"),
|
||||
CompositeKey: key,
|
||||
},
|
||||
)
|
||||
@ -87,14 +87,14 @@ func GetRepositoryFileByHash(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
algorithm := strings.ToLower(ctx.Params("algorithm"))
|
||||
algorithm := strings.ToLower(ctx.PathParam("algorithm"))
|
||||
if algorithm == "md5sum" {
|
||||
algorithm = "md5"
|
||||
}
|
||||
|
||||
pfs, _, err := packages_model.SearchFiles(ctx, &packages_model.PackageFileSearchOptions{
|
||||
VersionID: pv.ID,
|
||||
Hash: strings.ToLower(ctx.Params("hash")),
|
||||
Hash: strings.ToLower(ctx.PathParam("hash")),
|
||||
HashAlgorithm: algorithm,
|
||||
})
|
||||
if err != nil {
|
||||
@ -120,8 +120,8 @@ func GetRepositoryFileByHash(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func UploadPackageFile(ctx *context.Context) {
|
||||
distribution := strings.TrimSpace(ctx.Params("distribution"))
|
||||
component := strings.TrimSpace(ctx.Params("component"))
|
||||
distribution := strings.TrimSpace(ctx.PathParam("distribution"))
|
||||
component := strings.TrimSpace(ctx.PathParam("component"))
|
||||
if distribution == "" || component == "" {
|
||||
apiError(ctx, http.StatusBadRequest, "invalid distribution or component")
|
||||
return
|
||||
@ -207,8 +207,8 @@ func UploadPackageFile(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
name := ctx.Params("name")
|
||||
version := ctx.Params("version")
|
||||
name := ctx.PathParam("name")
|
||||
version := ctx.PathParam("version")
|
||||
|
||||
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
|
||||
ctx,
|
||||
@ -219,8 +219,8 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
Version: version,
|
||||
},
|
||||
&packages_service.PackageFileInfo{
|
||||
Filename: fmt.Sprintf("%s_%s_%s.deb", name, version, ctx.Params("architecture")),
|
||||
CompositeKey: fmt.Sprintf("%s|%s", ctx.Params("distribution"), ctx.Params("component")),
|
||||
Filename: fmt.Sprintf("%s_%s_%s.deb", name, version, ctx.PathParam("architecture")),
|
||||
CompositeKey: fmt.Sprintf("%s|%s", ctx.PathParam("distribution"), ctx.PathParam("component")),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
@ -240,11 +240,11 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
}
|
||||
|
||||
func DeletePackageFile(ctx *context.Context) {
|
||||
distribution := ctx.Params("distribution")
|
||||
component := ctx.Params("component")
|
||||
name := ctx.Params("name")
|
||||
version := ctx.Params("version")
|
||||
architecture := ctx.Params("architecture")
|
||||
distribution := ctx.PathParam("distribution")
|
||||
component := ctx.PathParam("component")
|
||||
name := ctx.PathParam("name")
|
||||
version := ctx.PathParam("version")
|
||||
architecture := ctx.PathParam("architecture")
|
||||
|
||||
owner := ctx.Package.Owner
|
||||
|
||||
|
@ -36,11 +36,11 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
&packages_service.PackageInfo{
|
||||
Owner: ctx.Package.Owner,
|
||||
PackageType: packages_model.TypeGeneric,
|
||||
Name: ctx.Params("packagename"),
|
||||
Version: ctx.Params("packageversion"),
|
||||
Name: ctx.PathParam("packagename"),
|
||||
Version: ctx.PathParam("packageversion"),
|
||||
},
|
||||
&packages_service.PackageFileInfo{
|
||||
Filename: ctx.Params("filename"),
|
||||
Filename: ctx.PathParam("filename"),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
@ -71,8 +71,8 @@ func isValidFileName(filename string) bool {
|
||||
// UploadPackage uploads the specific generic package.
|
||||
// Duplicated packages get rejected.
|
||||
func UploadPackage(ctx *context.Context) {
|
||||
packageName := ctx.Params("packagename")
|
||||
filename := ctx.Params("filename")
|
||||
packageName := ctx.PathParam("packagename")
|
||||
filename := ctx.PathParam("filename")
|
||||
|
||||
if !isValidPackageName(packageName) {
|
||||
apiError(ctx, http.StatusBadRequest, errors.New("invalid package name"))
|
||||
@ -84,7 +84,7 @@ func UploadPackage(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
packageVersion := ctx.Params("packageversion")
|
||||
packageVersion := ctx.PathParam("packageversion")
|
||||
if packageVersion != strings.TrimSpace(packageVersion) {
|
||||
apiError(ctx, http.StatusBadRequest, errors.New("invalid package version"))
|
||||
return
|
||||
@ -150,8 +150,8 @@ func DeletePackage(ctx *context.Context) {
|
||||
&packages_service.PackageInfo{
|
||||
Owner: ctx.Package.Owner,
|
||||
PackageType: packages_model.TypeGeneric,
|
||||
Name: ctx.Params("packagename"),
|
||||
Version: ctx.Params("packageversion"),
|
||||
Name: ctx.PathParam("packagename"),
|
||||
Version: ctx.PathParam("packageversion"),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
@ -169,12 +169,12 @@ func DeletePackage(ctx *context.Context) {
|
||||
// DeletePackageFile deletes the specific file of a generic package.
|
||||
func DeletePackageFile(ctx *context.Context) {
|
||||
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 {
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
@ -28,7 +28,7 @@ func apiError(ctx *context.Context, status int, obj any) {
|
||||
}
|
||||
|
||||
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 {
|
||||
apiError(ctx, http.StatusInternalServerError, err)
|
||||
return
|
||||
@ -50,7 +50,7 @@ func EnumeratePackageVersions(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 errors.Is(err, util.ErrNotExist) {
|
||||
apiError(ctx, http.StatusNotFound, err)
|
||||
@ -70,7 +70,7 @@ func PackageVersionMetadata(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 errors.Is(err, util.ErrNotExist) {
|
||||
apiError(ctx, http.StatusNotFound, err)
|
||||
@ -90,7 +90,7 @@ func PackageVersionGoModContent(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 errors.Is(err, util.ErrNotExist) {
|
||||
apiError(ctx, http.StatusNotFound, err)
|
||||
|
@ -101,14 +101,14 @@ func Index(ctx *context.Context) {
|
||||
|
||||
// DownloadPackageFile serves the content of a package
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
filename := ctx.Params("filename")
|
||||
filename := ctx.PathParam("filename")
|
||||
|
||||
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
Type: packages_model.TypeHelm,
|
||||
Name: packages_model.SearchValue{
|
||||
ExactMatch: true,
|
||||
Value: ctx.Params("package"),
|
||||
Value: ctx.PathParam("package"),
|
||||
},
|
||||
HasFileWithName: filename,
|
||||
IsInternal: optional.Some(false),
|
||||
|
@ -385,7 +385,7 @@ type parameters struct {
|
||||
}
|
||||
|
||||
func extractPathParameters(ctx *context.Context) (parameters, error) {
|
||||
parts := strings.Split(ctx.Params("*"), "/")
|
||||
parts := strings.Split(ctx.PathParam("*"), "/")
|
||||
|
||||
p := parameters{
|
||||
Filename: parts[len(parts)-1],
|
||||
|
@ -43,8 +43,8 @@ func apiError(ctx *context.Context, status int, obj any) {
|
||||
// packageNameFromParams gets the package name from the url parameters
|
||||
// Variations: /name/, /@scope/name/, /@scope%2Fname/
|
||||
func packageNameFromParams(ctx *context.Context) string {
|
||||
scope := ctx.Params("scope")
|
||||
id := ctx.Params("id")
|
||||
scope := ctx.PathParam("scope")
|
||||
id := ctx.PathParam("id")
|
||||
if scope != "" {
|
||||
return fmt.Sprintf("@%s/%s", scope, id)
|
||||
}
|
||||
@ -82,8 +82,8 @@ func PackageMetadata(ctx *context.Context) {
|
||||
// DownloadPackageFile serves the content of a package
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
packageName := packageNameFromParams(ctx)
|
||||
packageVersion := ctx.Params("version")
|
||||
filename := ctx.Params("filename")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
filename := ctx.PathParam("filename")
|
||||
|
||||
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
|
||||
ctx,
|
||||
@ -111,7 +111,7 @@ func DownloadPackageFile(ctx *context.Context) {
|
||||
|
||||
// DownloadPackageFileByName finds the version and serves the contents of a package
|
||||
func DownloadPackageFileByName(ctx *context.Context) {
|
||||
filename := ctx.Params("filename")
|
||||
filename := ctx.PathParam("filename")
|
||||
|
||||
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
|
||||
OwnerID: ctx.Package.Owner.ID,
|
||||
@ -254,7 +254,7 @@ func DeletePreview(ctx *context.Context) {
|
||||
// DeletePackageVersion deletes the package version
|
||||
func DeletePackageVersion(ctx *context.Context) {
|
||||
packageName := packageNameFromParams(ctx)
|
||||
packageVersion := ctx.Params("version")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
|
||||
err := packages_service.RemovePackageVersionByNameAndVersion(
|
||||
ctx,
|
||||
@ -349,7 +349,7 @@ func AddPackageTag(ctx *context.Context) {
|
||||
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 {
|
||||
apiError(ctx, http.StatusBadRequest, err)
|
||||
return
|
||||
@ -370,7 +370,7 @@ func DeletePackageTag(ctx *context.Context) {
|
||||
}
|
||||
|
||||
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 {
|
||||
apiError(ctx, http.StatusBadRequest, err)
|
||||
return
|
||||
|
@ -226,7 +226,7 @@ func SearchServiceV3(ctx *context.Context) {
|
||||
|
||||
// https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index
|
||||
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)
|
||||
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
|
||||
func RegistrationLeafV2(ctx *context.Context) {
|
||||
packageName := ctx.Params("id")
|
||||
packageVersion := ctx.Params("version")
|
||||
packageName := ctx.PathParam("id")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
|
||||
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion)
|
||||
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
|
||||
func RegistrationLeafV3(ctx *context.Context) {
|
||||
packageName := ctx.Params("id")
|
||||
packageVersion := strings.TrimSuffix(ctx.Params("version"), ".json")
|
||||
packageName := ctx.PathParam("id")
|
||||
packageVersion := strings.TrimSuffix(ctx.PathParam("version"), ".json")
|
||||
|
||||
pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeNuGet, packageName, packageVersion)
|
||||
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
|
||||
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)
|
||||
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-content-nupkg
|
||||
func DownloadPackageFile(ctx *context.Context) {
|
||||
packageName := ctx.Params("id")
|
||||
packageVersion := ctx.Params("version")
|
||||
filename := ctx.Params("filename")
|
||||
packageName := ctx.PathParam("id")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
filename := ctx.PathParam("filename")
|
||||
|
||||
s, u, pf, err := packages_service.GetFileStreamByPackageNameAndVersion(
|
||||
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
|
||||
func DownloadSymbolFile(ctx *context.Context) {
|
||||
filename := ctx.Params("filename")
|
||||
guid := ctx.Params("guid")[:32]
|
||||
filename2 := ctx.Params("filename2")
|
||||
filename := ctx.PathParam("filename")
|
||||
guid := ctx.PathParam("guid")[:32]
|
||||
filename2 := ctx.PathParam("filename2")
|
||||
|
||||
if filename != filename2 {
|
||||
apiError(ctx, http.StatusBadRequest, nil)
|
||||
@ -685,8 +685,8 @@ func DownloadSymbolFile(ctx *context.Context) {
|
||||
// DeletePackage hard deletes the package
|
||||
// https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package
|
||||
func DeletePackage(ctx *context.Context) {
|
||||
packageName := ctx.Params("id")
|
||||
packageVersion := ctx.Params("version")
|
||||
packageName := ctx.PathParam("id")
|
||||
packageVersion := ctx.PathParam("version")
|
||||
|
||||
err := packages_service.RemovePackageVersionByNameAndVersion(
|
||||
ctx,
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user