Documentation
¶
Index ¶
- Constants
- Variables
- func APIContexter() func(http.Handler) http.Handler
- func AccessLogger() func(http.Handler) http.Handler
- func CanWriteToBranch() func(ctx *Context)
- func CheckRepoScopedToken(ctx *Context, repo *repo_model.Repository, ...)
- func ComposeGoGetImport(ctx context.Context, owner, repo string) string
- func Contexter() func(next http.Handler) http.Handler
- func EarlyResponseForGoGetMeta(ctx *Context)
- func GenerateCsrfToken(key, userID, actionID string, now time.Time) string
- func GetImageCaptcha() *captcha.Captcha
- func GetOrganizationByParams(ctx *Context)
- func GetQueryBeforeSince(ctx *Base) (before, since int64, err error)
- func GitHookService() func(ctx *Context)
- func OrgAssignment(opts OrgAssignmentOptions) func(ctx *Context)
- func OverrideContext() func(http.Handler) http.Handler
- func PackageAssignment() func(ctx *Context)
- func PackageAssignmentAPI() func(ctx *APIContext)
- func PackageContexter() func(next http.Handler) http.Handler
- func ParseCsrfToken(token string) (issueTime time.Time, ok bool)
- func PrivateContexter() func(http.Handler) http.Handler
- func RedirectToRepo(ctx *Base, redirectRepoID int64)
- func RedirectToUser(ctx *Base, userName string, redirectUserID int64)
- func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext)
- func RepoAssignment(ctx *Context)
- func RepoMustNotBeArchived() func(ctx *Context)
- func RepoRefByDefaultBranch() func(*Context)
- func RepoRefByType(detectRefType git.RefType) func(*Context)
- func RepoRefForAPI(next http.Handler) http.Handler
- func RequireRepoAdmin() func(ctx *Context)
- func RequireUnitReader(unitTypes ...unit.Type) func(ctx *Context)
- func RequireUnitWriter(unitTypes ...unit.Type) func(ctx *Context)
- func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository)
- func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository)
- func SetCaptchaData(ctx *Context)
- func UserAssignmentAPI() func(ctx *APIContext)
- func UserAssignmentWeb() func(ctx *Context)
- func UserIDAssignmentAPI() func(ctx *APIContext)
- func ValidCsrfToken(token, key, userID, actionID string, now time.Time) bool
- func VerifyCaptcha(ctx *Context, tpl templates.TplName, form any)
- type APIConflict
- type APIContext
- func (ctx *APIContext) APIError(status int, obj any)
- func (ctx *APIContext) APIErrorInternal(err error)
- func (ctx *APIContext) APIErrorNotFound(objs ...any)
- func (ctx *APIContext) GetErrMsg() string
- func (ctx *APIContext) HasAPIError() bool
- func (ctx *APIContext) IsUserRepoAdmin() bool
- func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool
- func (ctx *APIContext) IsUserSiteAdmin() bool
- func (ctx *APIContext) NotFoundOrServerError(err error)
- func (ctx *APIContext) SetLinkHeader(total, pageSize int)
- type APIEmpty
- type APIError
- type APIForbiddenError
- type APIInvalidTopicsError
- type APINotFound
- type APIOrganization
- type APIRedirect
- type APIRepoArchivedError
- type APIString
- type APIValidationError
- type Base
- func (b *Base) AppendAccessControlExposeHeaders(names ...string)
- func (b *Base) FormBool(key string) bool
- func (b *Base) FormInt(key string) int
- func (b *Base) FormInt64(key string) int64
- func (b *Base) FormOptionalBool(key string) optional.Option[bool]
- func (b *Base) FormString(key string, def ...string) string
- func (b *Base) FormStrings(key string) []string
- func (b *Base) FormTrim(key string) string
- func (b *Base) HTTPError(status int, contents ...string)
- func (b *Base) JSON(status int, content any)
- func (b *Base) ParseMultipartForm() bool
- func (b *Base) PathParam(name string) string
- func (b *Base) PathParamInt64(p string) int64
- func (b *Base) PathParamRaw(name string) string
- func (b *Base) PlainText(status int, text string)
- func (b *Base) PlainTextBytes(status int, bs []byte)
- func (b *Base) Redirect(location string, status ...int)
- func (b *Base) RemoteAddr() string
- func (b *Base) RespHeader() http.Header
- func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions)
- func (b *Base) SetFormString(key, value string)
- func (b *Base) SetPathParam(name, value string)
- func (b *Base) SetServeHeaders(opt *ServeHeaderOptions)
- func (b *Base) SetTotalCountHeader(total int64)
- func (b *Base) Status(status int)
- func (b *Base) Tr(msg string, args ...any) template.HTML
- func (b *Base) TrN(cnt any, key1, keyN string, args ...any) template.HTML
- func (b *Base) Write(bs []byte) (int, error)
- func (b *Base) Written() bool
- func (b *Base) WrittenStatus() int
- type BaseContextKeyType
- type CSRFProtector
- type CommitFormOptions
- type Context
- func (ctx *Context) DeleteSiteCookie(name string)
- func (ctx *Context) DoerNeedTwoFactorAuth() bool
- func (ctx *Context) GetErrMsg() string
- func (ctx *Context) GetSiteCookie(name string) string
- func (ctx *Context) HTML(status int, name templates.TplName)
- func (ctx *Context) HasError() bool
- func (ctx *Context) IsUserSiteAdmin() bool
- func (ctx *Context) JSONError(msg any)
- func (ctx *Context) JSONErrorNotFound(optMsg ...string)
- func (ctx *Context) JSONOK()
- func (ctx *Context) JSONRedirect(redirect string)
- func (ctx *Context) JSONTemplate(tmpl templates.TplName)
- func (ctx *Context) NotFound(logErr error)
- func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error)
- func (ctx *Context) RedirectToCurrentSite(location ...string)
- func (ctx *Context) RenderToHTML(name templates.TplName, data any) (template.HTML, error)
- func (ctx *Context) RenderWithErr(msg any, tpl templates.TplName, form any)
- func (ctx *Context) ServerError(logMsg string, logErr error)
- func (ctx *Context) SetSiteCookie(name, value string, maxAge int)
- func (ctx *Context) UploadStream() (rd io.ReadCloser, needToClose bool, err error)
- type CsrfOptions
- type OrgAssignmentOptions
- type Organization
- type Package
- type Pagination
- type PrivateContext
- type PullRequest
- type Render
- type Repository
- func (r *Repository) CanCreateBranch() bool
- func (r *Repository) CanCreateIssueDependencies(ctx context.Context, user *user_model.User, isPull bool) bool
- func (r *Repository) CanUseTimetracker(ctx context.Context, issue *issues_model.Issue, user *user_model.User) bool
- func (r *Repository) CanWriteToBranch(ctx context.Context, user *user_model.User, branch string) bool
- func (r *Repository) GetCommitGraphsCount(ctx context.Context, hidePRRefs bool, branches, files []string) (int64, error)
- func (r *Repository) GetCommitsCount() (int64, error)
- func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (cfg *editorconfig.Editorconfig, warning, err error)
- func (r *Repository) GetObjectFormat() git.ObjectFormat
- func (r *Repository) RefTypeNameSubURL() string
- type Response
- type ResponseWriter
- type ServeHeaderOptions
- type TemplateContext
- type ValidateContext
Constants ¶
const ( CsrfHeaderName = "X-Csrf-Token" CsrfFormName = "_csrf" )
const CookieNameFlash = "gitea_flash"
const CsrfTokenTimeout = 24 * time.Hour
CsrfTokenTimeout represents the duration that XSRF tokens are valid. It is exported so clients may set cookie timeouts that match generated tokens.
Variables ¶
var CsrfTokenRegenerationInterval = 10 * time.Minute
CsrfTokenRegenerationInterval is the interval between token generations, old tokens are still valid before CsrfTokenTimeout
var WebContextKey = webContextKeyType{}
Functions ¶
func APIContexter ¶
APIContexter returns APIContext middleware
func AccessLogger ¶
AccessLogger returns a middleware to log access logger
func CanWriteToBranch ¶
func CanWriteToBranch() func(ctx *Context)
CanWriteToBranch checks if the user is allowed to write to the branch of the repo
func CheckRepoScopedToken ¶
func CheckRepoScopedToken(ctx *Context, repo *repo_model.Repository, level auth_model.AccessTokenScopeLevel)
CheckRepoScopedToken check whether personal access token has repo scope
func ComposeGoGetImport ¶
ComposeGoGetImport returns go-get-import meta content.
func EarlyResponseForGoGetMeta ¶
func EarlyResponseForGoGetMeta(ctx *Context)
EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200 if user does not have actual access to the requested repository, or the owner or repository does not exist at all. This is particular a workaround for "go get" command which does not respect .netrc file.
func GenerateCsrfToken ¶
GenerateCsrfToken returns a URL-safe secure XSRF token that expires in CsrfTokenTimeout hours. key is a secret key for your application. userID is a unique identifier for the user. actionID is the action the user is taking (e.g. POSTing to a particular path).
func GetImageCaptcha ¶
GetImageCaptcha returns global image captcha
func GetOrganizationByParams ¶
func GetOrganizationByParams(ctx *Context)
func GetQueryBeforeSince ¶
GetQueryBeforeSince return parsed time (unix format) from URL query's before and since
func GitHookService ¶
func GitHookService() func(ctx *Context)
GitHookService checks if repository Git hooks service has been enabled.
func OrgAssignment ¶
func OrgAssignment(opts OrgAssignmentOptions) func(ctx *Context)
OrgAssignment returns a middleware to handle organization assignment
func OverrideContext ¶
OverrideContext overrides the underlying request context for Done() etc. This function should be used when there is a need for work to continue even if the request has been cancelled. Primarily this affects hook/post-receive and hook/proc-receive both of which need to continue working even if the underlying request has timed out from the ssh/http push
func PackageAssignment ¶
func PackageAssignment() func(ctx *Context)
PackageAssignment returns a middleware to handle Context.Package assignment
func PackageAssignmentAPI ¶
func PackageAssignmentAPI() func(ctx *APIContext)
PackageAssignmentAPI returns a middleware to handle Context.Package assignment
func PackageContexter ¶
PackageContexter initializes a package context for a request.
func RedirectToRepo ¶
RedirectToRepo redirect to a differently-named repository
func RedirectToUser ¶
RedirectToUser redirect to a differently-named user
func ReferencesGitRepo ¶
func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext)
ReferencesGitRepo injects the GitRepo into the Context you can optional skip the IsEmpty check
func RepoAssignment ¶
func RepoAssignment(ctx *Context)
RepoAssignment returns a middleware to handle repository assignment
func RepoMustNotBeArchived ¶
func RepoMustNotBeArchived() func(ctx *Context)
RepoMustNotBeArchived checks if a repo is archived
func RepoRefByDefaultBranch ¶
func RepoRefByDefaultBranch() func(*Context)
func RepoRefByType ¶
RepoRefByType handles repository reference name for a specific type of repository reference
func RepoRefForAPI ¶
RepoRefForAPI handles repository reference names when the ref name is not explicitly given
func RequireRepoAdmin ¶
func RequireRepoAdmin() func(ctx *Context)
RequireRepoAdmin returns a middleware for requiring repository admin permission
func RequireUnitReader ¶
RequireUnitReader returns a middleware for requiring repository write to one of the unit permission
func RequireUnitWriter ¶
RequireUnitWriter returns a middleware for requiring repository write to one of the unit permission
func RetrieveBaseRepo ¶
func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository)
RetrieveBaseRepo retrieves base repository
func RetrieveTemplateRepo ¶
func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository)
RetrieveTemplateRepo retrieves template repository used to generate this repository
func UserAssignmentAPI ¶
func UserAssignmentAPI() func(ctx *APIContext)
UserAssignmentAPI returns a middleware to handle context-user assignment for api routes
func UserAssignmentWeb ¶
func UserAssignmentWeb() func(ctx *Context)
UserAssignmentWeb returns a middleware to handle context-user assignment for web routes
func UserIDAssignmentAPI ¶
func UserIDAssignmentAPI() func(ctx *APIContext)
UserIDAssignmentAPI returns a middleware to handle context-user assignment for api routes
func ValidCsrfToken ¶
ValidCsrfToken returns true if token is a valid and unexpired token returned by Generate.
Types ¶
type APIConflict ¶
type APIConflict struct{}
APIConflict is a conflict empty response swagger:response conflict
type APIContext ¶
type APIContext struct {
*Base
Cache cache.StringCache
Doer *user_model.User // current signed-in user
IsSigned bool
IsBasicAuth bool
ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
Repo *Repository
Org *APIOrganization
Package *Package
PublicOnly bool // Whether the request is for a public endpoint
}
APIContext is a specific context for API service ATTENTION: This struct should never be manually constructed in routes/services, it has many internal details which should be carefully prepared by the framework. If it is abused, it would cause strange bugs like panic/resource-leak.
func GetAPIContext ¶
func GetAPIContext(req *http.Request) *APIContext
GetAPIContext returns a context for API routes
func (*APIContext) APIError ¶
func (ctx *APIContext) APIError(status int, obj any)
APIError responds with an error message to client with given obj as the message. If status is 500, also it prints error to log.
func (*APIContext) APIErrorInternal ¶
func (ctx *APIContext) APIErrorInternal(err error)
APIErrorInternal responds with error message, status is 500
func (*APIContext) APIErrorNotFound ¶
func (ctx *APIContext) APIErrorNotFound(objs ...any)
APIErrorNotFound handles 404s for APIContext String will replace message, errors will be added to a slice
func (*APIContext) GetErrMsg ¶
func (ctx *APIContext) GetErrMsg() string
GetErrMsg returns error message in form validation.
func (*APIContext) HasAPIError ¶
func (ctx *APIContext) HasAPIError() bool
HasAPIError returns true if error occurs in form validation.
func (*APIContext) IsUserRepoAdmin ¶
func (ctx *APIContext) IsUserRepoAdmin() bool
IsUserRepoAdmin returns true if current user is admin in current repo
func (*APIContext) IsUserRepoWriter ¶
func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool
IsUserRepoWriter returns true if current user has "write" privilege in current repo
func (*APIContext) IsUserSiteAdmin ¶
func (ctx *APIContext) IsUserSiteAdmin() bool
IsUserSiteAdmin returns true if current user is a site admin
func (*APIContext) NotFoundOrServerError ¶
func (ctx *APIContext) NotFoundOrServerError(err error)
NotFoundOrServerError use error check function to determine if the error is about not found. It responds with 404 status code for not found error, or error context description for logging purpose of 500 server error.
func (*APIContext) SetLinkHeader ¶
func (ctx *APIContext) SetLinkHeader(total, pageSize int)
SetLinkHeader sets pagination link header by given total number and page size.
type APIForbiddenError ¶
type APIForbiddenError struct {
APIError
}
APIForbiddenError is a forbidden error response swagger:response forbidden
type APIInvalidTopicsError ¶
type APIInvalidTopicsError struct {
Message string `json:"message"`
InvalidTopics []string `json:"invalidTopics"`
}
APIInvalidTopicsError is error format response to invalid topics swagger:response invalidTopicsError
type APINotFound ¶
type APINotFound struct{}
APINotFound is a not found empty response swagger:response notFound
type APIOrganization ¶
type APIOrganization struct {
Organization *organization.Organization
Team *organization.Team
}
APIOrganization contains organization and team
type APIRedirect ¶
type APIRedirect struct{}
APIRedirect is a redirect response swagger:response redirect
type APIRepoArchivedError ¶
type APIRepoArchivedError struct {
APIError
}
APIRepoArchivedError is an error that is raised when an archived repo should be modified swagger:response repoArchivedError
type APIValidationError ¶
APIValidationError is error format response related to input validation swagger:response validationError
type Base ¶
type Base struct {
reqctx.RequestContext
Resp ResponseWriter
Req *http.Request
// Data is prepared by ContextDataStore middleware, this field only refers to the pre-created/prepared ContextData.
// Although it's mainly used for MVC templates, sometimes it's also used to pass data between middlewares/handler
Data reqctx.ContextData
// Locale is mainly for Web context, although the API context also uses it in some cases: message response, form validation
Locale translation.Locale
}
Base is the base context for all web handlers ATTENTION: This struct should never be manually constructed in routes/services, it has many internal details which should be carefully prepared by the framework. If it is abused, it would cause strange bugs like panic/resource-leak.
func NewBaseContext ¶
func NewBaseContext(resp http.ResponseWriter, req *http.Request) *Base
func NewBaseContextForTest ¶
func NewBaseContextForTest(resp http.ResponseWriter, req *http.Request) *Base
func (*Base) AppendAccessControlExposeHeaders ¶
AppendAccessControlExposeHeaders append headers by name to "Access-Control-Expose-Headers" header
func (*Base) FormBool ¶
FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
func (*Base) FormInt64 ¶
FormInt64 returns the first value for the provided key in the form as an int64
func (*Base) FormOptionalBool ¶
FormOptionalBool returns an optional.Some(true) or optional.Some(false) if the value for the provided key exists in the form else it returns optional.None[bool]()
func (*Base) FormString ¶
FormString returns the first value matching the provided key in the form as a string It works the same as http.Request.FormValue: try urlencoded request body first, then query string, then multipart form body
func (*Base) FormStrings ¶
FormStrings returns a values for the key in the form (including query parameters), similar to FormString
func (*Base) FormTrim ¶
FormTrim returns the first value for the provided key in the form as a space trimmed string
func (*Base) HTTPError ¶
HTTPError returned an error to web browser FIXME: many calls to this HTTPError are not right: it shouldn't expose err.Error() directly, it doesn't accept more than one content
func (*Base) ParseMultipartForm ¶
func (*Base) PathParam ¶
PathParam returns the param in request path, eg: "/{var}" => "/a%2fb", then `var == "a/b"`
func (*Base) PathParamInt64 ¶
PathParamInt64 returns the param in request path as int64
func (*Base) PathParamRaw ¶
PathParamRaw returns the raw param in request path, eg: "/{var}" => "/a%2fb", then `var == "a%2fb"`
func (*Base) PlainTextBytes ¶
PlainTextBytes renders bytes as plain text
func (*Base) RemoteAddr ¶
RemoteAddr returns the client machine ip address
func (*Base) RespHeader ¶
RespHeader returns the response header
func (*Base) ServeContent ¶
func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions)
ServeContent serves content to http request
func (*Base) SetFormString ¶
func (*Base) SetPathParam ¶
SetPathParam set request path params into routes
func (*Base) SetServeHeaders ¶
func (b *Base) SetServeHeaders(opt *ServeHeaderOptions)
func (*Base) SetTotalCountHeader ¶
SetTotalCountHeader set "X-Total-Count" header
func (*Base) WrittenStatus ¶
type CSRFProtector ¶
type CSRFProtector interface {
// PrepareForSessionUser prepares the csrf protector for the current session user.
PrepareForSessionUser(ctx *Context)
// Validate validates the csrf token in http context.
Validate(ctx *Context)
// DeleteCookie deletes the csrf cookie
DeleteCookie(ctx *Context)
}
CSRFProtector represents a CSRF protector and is used to get the current token and validate the token.
func NewCSRFProtector ¶
func NewCSRFProtector(opt CsrfOptions) CSRFProtector
type CommitFormOptions ¶
type CommitFormOptions struct {
NeedFork bool
TargetRepo *repo_model.Repository
TargetFormAction string
WillSubmitToFork bool
CanCommitToBranch bool
UserCanPush bool
RequireSigned bool
WillSign bool
SigningKeyFormDisplay string
WontSignReason string
CanCreatePullRequest bool
CanCreateBasePullRequest bool
}
func PrepareCommitFormOptions ¶
func PrepareCommitFormOptions(ctx *Context, doer *user_model.User, targetRepo *repo_model.Repository, doerRepoPerm access_model.Permission, refName git.RefName) (*CommitFormOptions, error)
type Context ¶
type Context struct {
*Base
TemplateContext TemplateContext
Render Render
PageData map[string]any // data used by JavaScript modules in one page, it's `window.config.pageData`
Cache cache.StringCache
Csrf CSRFProtector
Flash *middleware.Flash
Session session.Store
Link string // current request URL (without query string)
Doer *user_model.User // current signed-in user
IsSigned bool
IsBasicAuth bool
ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
Repo *Repository
Org *Organization
Package *Package
}
Context represents context of a web request. ATTENTION: This struct should never be manually constructed in routes/services, it has many internal details which should be carefully prepared by the framework. If it is abused, it would cause strange bugs like panic/resource-leak.
func GetWebContext ¶
func (*Context) DeleteSiteCookie ¶
DeleteSiteCookie convenience function to delete most cookies consistently CSRF and a few others are the exception here
func (*Context) DoerNeedTwoFactorAuth ¶
func (*Context) GetSiteCookie ¶
GetSiteCookie returns given cookie value from request header.
func (*Context) HasError ¶
HasError returns true if error occurs in form validation. Attention: this function changes ctx.Data and ctx.Flash If HasError is called, then before Redirect, the error message should be stored by ctx.Flash.Error(ctx.GetErrMsg()) again.
func (*Context) IsUserSiteAdmin ¶
IsUserSiteAdmin returns true if current user is a site admin
func (*Context) JSONErrorNotFound ¶
func (*Context) JSONRedirect ¶
func (*Context) JSONTemplate ¶
JSONTemplate renders the template as JSON response keep in mind that the template is processed in HTML context, so JSON things should be handled carefully, e.g.: use JSEscape
func (*Context) NotFound ¶
NotFound displays a 404 (Not Found) page and prints the given error, if any.
func (*Context) NotFoundOrServerError ¶
NotFoundOrServerError use error check function to determine if the error is about not found. It responds with 404 status code for not found error, or error context description for logging purpose of 500 server error. TODO: remove the "errCheck" and use util.ErrNotFound to check
func (*Context) RedirectToCurrentSite ¶
RedirectToCurrentSite redirects to first not empty URL which belongs to current site
func (*Context) RenderToHTML ¶
RenderToHTML renders the template content to a HTML string
func (*Context) RenderWithErr ¶
RenderWithErr used for page has form validation but need to prompt error to users.
func (*Context) ServerError ¶
ServerError displays a 500 (Internal Server Error) page and prints the given error, if any.
func (*Context) SetSiteCookie ¶
SetSiteCookie convenience function to set most cookies consistently CSRF and a few others are the exception here
func (*Context) UploadStream ¶
func (ctx *Context) UploadStream() (rd io.ReadCloser, needToClose bool, err error)
UploadStream returns the request body or the first form file Only form files need to get closed.
type CsrfOptions ¶
type CsrfOptions struct {
// The global secret value used to generate Tokens.
Secret string
// Cookie value used to set and get token.
Cookie string
// Cookie domain.
CookieDomain string
// Cookie path.
CookiePath string
CookieHTTPOnly bool
// SameSite set the cookie SameSite type
SameSite http.SameSite
// Set the Secure flag to true on the cookie.
Secure bool
// contains filtered or unexported fields
}
CsrfOptions maintains options to manage behavior of Generate.
type OrgAssignmentOptions ¶
type Organization ¶
type Organization struct {
IsOwner bool
IsMember bool
IsTeamMember bool // Is member of team.
IsTeamAdmin bool // In owner team or team that has admin permission level.
Organization *organization.Organization
OrgLink string
CanCreateOrgRepo bool
Team *organization.Team
Teams []*organization.Team
}
Organization contains organization context
func (*Organization) CanReadUnit ¶
func (org *Organization) CanReadUnit(ctx *Context, unitType unit.Type) bool
func (*Organization) CanWriteUnit ¶
func (org *Organization) CanWriteUnit(ctx *Context, unitType unit.Type) bool
type Package ¶
type Package struct {
Owner *user_model.User
AccessMode perm.AccessMode
Descriptor *packages_model.PackageDescriptor
}
Package contains owner, access mode and optional the package descriptor
type Pagination ¶
Pagination provides a pagination via paginator.Paginator and additional configurations for the link params used in rendering
func NewPagination ¶
func NewPagination(total, pagingNum, current, numPages int) *Pagination
NewPagination creates a new instance of the Pagination struct. "pagingNum" is "page size" or "limit", "current" is "page" total=-1 means only showing prev/next
func (*Pagination) AddParamFromQuery ¶
func (p *Pagination) AddParamFromQuery(q url.Values)
func (*Pagination) AddParamFromRequest ¶
func (p *Pagination) AddParamFromRequest(req *http.Request)
func (*Pagination) GetParams ¶
func (p *Pagination) GetParams() template.URL
GetParams returns the configured URL params
func (*Pagination) WithCurRows ¶
func (p *Pagination) WithCurRows(n int) *Pagination
type PrivateContext ¶
type PrivateContext struct {
*Base
Override context.Context
Repo *Repository
}
PrivateContext represents a context for private routes
func GetPrivateContext ¶
func GetPrivateContext(req *http.Request) *PrivateContext
func (*PrivateContext) Deadline ¶
func (ctx *PrivateContext) Deadline() (deadline time.Time, ok bool)
func (*PrivateContext) Done ¶
func (ctx *PrivateContext) Done() <-chan struct{}
func (*PrivateContext) Err ¶
func (ctx *PrivateContext) Err() error
type PullRequest ¶
type PullRequest struct {
BaseRepo *repo_model.Repository
Allowed bool // it only used by the web tmpl: "PullRequestCtx.Allowed"
SameRepo bool // it only used by the web tmpl: "PullRequestCtx.SameRepo"
}
PullRequest contains information to make a pull request
type Render ¶
type Render interface {
TemplateLookup(tmpl string, templateCtx context.Context) (templates.TemplateExecutor, error)
HTML(w io.Writer, status int, name templates.TplName, data any, templateCtx context.Context) error
}
Render represents a template render
type Repository ¶
type Repository struct {
access_model.Permission
Repository *repo_model.Repository
Owner *user_model.User
RepoLink string
GitRepo *git.Repository
// RefFullName is the full ref name that the user is viewing
RefFullName git.RefName
BranchName string // it is the RefFullName's short name if its type is "branch"
TreePath string
// Commit it is always set to the commit for the branch or tag, or just the commit that the user is viewing
Commit *git.Commit
CommitID string
CommitsCount int64
PullRequest *PullRequest
}
Repository contains information to operate a repository
func (*Repository) CanCreateBranch ¶
func (r *Repository) CanCreateBranch() bool
CanCreateBranch returns true if repository is editable and user has proper access level.
func (*Repository) CanCreateIssueDependencies ¶
func (r *Repository) CanCreateIssueDependencies(ctx context.Context, user *user_model.User, isPull bool) bool
CanCreateIssueDependencies returns whether or not a user can create dependencies.
func (*Repository) CanUseTimetracker ¶
func (r *Repository) CanUseTimetracker(ctx context.Context, issue *issues_model.Issue, user *user_model.User) bool
CanUseTimetracker returns whether a user can use the timetracker.
func (*Repository) CanWriteToBranch ¶
func (r *Repository) CanWriteToBranch(ctx context.Context, user *user_model.User, branch string) bool
CanWriteToBranch checks if the branch is writable by the user
func (*Repository) GetCommitGraphsCount ¶
func (r *Repository) GetCommitGraphsCount(ctx context.Context, hidePRRefs bool, branches, files []string) (int64, error)
GetCommitGraphsCount returns cached commit count for current view
func (*Repository) GetCommitsCount ¶
func (r *Repository) GetCommitsCount() (int64, error)
GetCommitsCount returns cached commit count for current view
func (*Repository) GetEditorconfig ¶
func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (cfg *editorconfig.Editorconfig, warning, err error)
GetEditorconfig returns the .editorconfig definition if found in the HEAD of the default repo branch.
func (*Repository) GetObjectFormat ¶
func (r *Repository) GetObjectFormat() git.ObjectFormat
func (*Repository) RefTypeNameSubURL ¶
func (r *Repository) RefTypeNameSubURL() string
RefTypeNameSubURL makes a sub-url for the current ref (branch/tag/commit) field, for example: * "branch/master" * "tag/v1.0.0" * "commit/123456" It is usually used to construct a link like ".../src/{{RefTypeNameSubURL}}/{{PathEscapeSegments TreePath}}"
type Response ¶
type Response struct {
http.ResponseWriter
// contains filtered or unexported fields
}
Response represents a response
func WrapResponseWriter ¶
func WrapResponseWriter(resp http.ResponseWriter) *Response
func (*Response) Before ¶
func (r *Response) Before(fn func(ResponseWriter))
Before allows for a function to be called before the ResponseWriter has been written to. This is useful for setting headers or any other operations that must happen before a response has been written.
func (*Response) WriteHeader ¶
WriteHeader write status code
func (*Response) WrittenSize ¶
func (*Response) WrittenStatus ¶
WrittenStatus returned status code written
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter // provides Header/Write/WriteHeader
http.Flusher // provides Flush
web_types.ResponseStatusProvider // provides WrittenStatus
Before(fn func(ResponseWriter))
WrittenSize() int
}
ResponseWriter represents a response writer for HTTP
type ServeHeaderOptions ¶
type ServeHeaderOptions httplib.ServeHeaderOptions
type TemplateContext ¶
func NewTemplateContext ¶
func NewTemplateContext(ctx context.Context) TemplateContext
func NewTemplateContextForWeb ¶
func NewTemplateContextForWeb(ctx *Context) TemplateContext
func (TemplateContext) Done ¶
func (c TemplateContext) Done() <-chan struct{}
func (TemplateContext) Err ¶
func (c TemplateContext) Err() error
func (TemplateContext) Value ¶
func (c TemplateContext) Value(key any) any
type ValidateContext ¶
type ValidateContext struct {
*Base
}
ValidateContext is a special context for form validation middleware. It may be different from other contexts.
func GetValidateContext ¶
func GetValidateContext(req *http.Request) (ctx *ValidateContext)
GetValidateContext gets a context for middleware form validation