aliases.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. package iris
  2. import (
  3. "io/fs"
  4. "net/http"
  5. "net/url"
  6. "path"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "github.com/kataras/iris/v12/cache"
  11. "github.com/kataras/iris/v12/context"
  12. "github.com/kataras/iris/v12/core/handlerconv"
  13. "github.com/kataras/iris/v12/core/host"
  14. "github.com/kataras/iris/v12/core/router"
  15. "github.com/kataras/iris/v12/hero"
  16. "github.com/kataras/iris/v12/view"
  17. )
  18. var (
  19. // BuildRevision holds the vcs commit id information of the program's build.
  20. // To display the Iris' version please use the iris.Version constant instead.
  21. // Available at go version 1.18+
  22. BuildRevision = context.BuildRevision
  23. // BuildTime holds the vcs commit time information of the program's build.
  24. // Available at go version 1.18+
  25. BuildTime = context.BuildTime
  26. )
  27. // SameSite attributes.
  28. const (
  29. SameSiteDefaultMode = http.SameSiteDefaultMode
  30. SameSiteLaxMode = http.SameSiteLaxMode
  31. SameSiteStrictMode = http.SameSiteStrictMode
  32. SameSiteNoneMode = http.SameSiteNoneMode
  33. )
  34. type (
  35. // Context is the middle-man server's "object" for the clients.
  36. //
  37. // A New context is being acquired from a sync.Pool on each connection.
  38. // The Context is the most important thing on the iris's http flow.
  39. //
  40. // Developers send responses to the client's request through a Context.
  41. // Developers get request information from the client's request by a Context.
  42. Context = *context.Context
  43. // ViewEngine is an alias of `context.ViewEngine`.
  44. // See HTML, Blocks, Django, Jet, Pug, Ace, Handlebars and e.t.c.
  45. ViewEngine = context.ViewEngine
  46. // UnmarshalerFunc a shortcut, an alias for the `context#UnmarshalerFunc` type
  47. // which implements the `context#Unmarshaler` interface for reading request's body
  48. // via custom decoders, most of them already implement the `context#UnmarshalerFunc`
  49. // like the json.Unmarshal, xml.Unmarshal, yaml.Unmarshal and every library which
  50. // follows the best practises and is aligned with the Go standards.
  51. //
  52. // See 'context#UnmarshalBody` for more.
  53. //
  54. // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-custom-via-unmarshaler/main.go
  55. UnmarshalerFunc = context.UnmarshalerFunc
  56. // DecodeFunc is a generic type of decoder function.
  57. // When the returned error is not nil the decode operation
  58. // is terminated and the error is received by the ReadJSONStream method,
  59. // otherwise it continues to read the next available object.
  60. // Look the `Context.ReadJSONStream` method.
  61. //
  62. // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-json-stream.
  63. DecodeFunc = context.DecodeFunc
  64. // A Handler responds to an HTTP request.
  65. // It writes reply headers and data to the Context.ResponseWriter() and then return.
  66. // Returning signals that the request is finished;
  67. // it is not valid to use the Context after or concurrently with the completion of the Handler call.
  68. //
  69. // Depending on the HTTP client software, HTTP protocol version,
  70. // and any intermediaries between the client and the iris server,
  71. // it may not be possible to read from the Context.Request().Body after writing to the context.ResponseWriter().
  72. // Cautious handlers should read the Context.Request().Body first, and then reply.
  73. //
  74. // Except for reading the body, handlers should not modify the provided Context.
  75. //
  76. // If Handler panics, the server (the caller of Handler) assumes that the effect of the panic was isolated to the active request.
  77. // It recovers the panic, logs a stack trace to the server error log, and hangs up the connection.
  78. Handler = context.Handler
  79. // Filter is just a type of func(Context) bool which reports whether an action must be performed
  80. // based on the incoming request.
  81. //
  82. // See `NewConditionalHandler` for more.
  83. // An alias for the `context/Filter`.
  84. Filter = context.Filter
  85. // A Map is an alias of map[string]interface{}.
  86. Map = context.Map
  87. // User is a generic view of an authorized client.
  88. // See `Context.User` and `SetUser` methods for more.
  89. // An alias for the `context/User` type.
  90. User = context.User
  91. // SimpleUser is a simple implementation of the User interface.
  92. SimpleUser = context.SimpleUser
  93. // Problem Details for HTTP APIs.
  94. // Pass a Problem value to `context.Problem` to
  95. // write an "application/problem+json" response.
  96. //
  97. // Read more at: https://github.com/kataras/iris/blob/main/_examples/routing/http-errors.
  98. //
  99. // It is an alias of the `context#Problem` type.
  100. Problem = context.Problem
  101. // ProblemOptions the optional settings when server replies with a Problem.
  102. // See `Context.Problem` method and `Problem` type for more details.
  103. //
  104. // It is an alias of the `context#ProblemOptions` type.
  105. ProblemOptions = context.ProblemOptions
  106. // JSON the optional settings for JSON renderer.
  107. //
  108. // It is an alias of the `context#JSON` type.
  109. JSON = context.JSON
  110. // JSONReader holds the JSON decode options of the `Context.ReadJSON, ReadBody` methods.
  111. //
  112. // It is an alias of the `context#JSONReader` type.
  113. JSONReader = context.JSONReader
  114. // JSONP the optional settings for JSONP renderer.
  115. //
  116. // It is an alias of the `context#JSONP` type.
  117. JSONP = context.JSONP
  118. // ProtoMarshalOptions is a type alias for protojson.MarshalOptions.
  119. ProtoMarshalOptions = context.ProtoMarshalOptions
  120. // ProtoUnmarshalOptions is a type alias for protojson.UnmarshalOptions.
  121. ProtoUnmarshalOptions = context.ProtoUnmarshalOptions
  122. // XML the optional settings for XML renderer.
  123. //
  124. // It is an alias of the `context#XML` type.
  125. XML = context.XML
  126. // Markdown the optional settings for Markdown renderer.
  127. // See `Context.Markdown` for more.
  128. //
  129. // It is an alias of the `context#Markdown` type.
  130. Markdown = context.Markdown
  131. // Supervisor is a shortcut of the `host#Supervisor`.
  132. // Used to add supervisor configurators on common Runners
  133. // without the need of importing the `core/host` package.
  134. Supervisor = host.Supervisor
  135. // Party is just a group joiner of routes which have the same prefix and share same middleware(s) also.
  136. // Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun.
  137. //
  138. // Look the `core/router#APIBuilder` for its implementation.
  139. //
  140. // A shortcut for the `core/router#Party`, useful when `PartyFunc` is being used.
  141. Party = router.Party
  142. // APIContainer is a wrapper of a common `Party` featured by Dependency Injection.
  143. // See `Party.ConfigureContainer` for more.
  144. //
  145. // A shortcut for the `core/router#APIContainer`.
  146. APIContainer = router.APIContainer
  147. // ResultHandler describes the function type which should serve the "v" struct value.
  148. // See `APIContainer.UseResultHandler`.
  149. ResultHandler = hero.ResultHandler
  150. // DirOptions contains the optional settings that
  151. // `FileServer` and `Party#HandleDir` can use to serve files and assets.
  152. // A shortcut for the `router.DirOptions`, useful when `FileServer` or `HandleDir` is being used.
  153. DirOptions = router.DirOptions
  154. // DirCacheOptions holds the options for the cached file system.
  155. // See `DirOptions`.
  156. DirCacheOptions = router.DirCacheOptions
  157. // DirListRichOptions the options for the `DirListRich` helper function.
  158. // A shortcut for the `router.DirListRichOptions`.
  159. // Useful when `DirListRich` function is passed to `DirOptions.DirList` field.
  160. DirListRichOptions = router.DirListRichOptions
  161. // Attachments options for files to be downloaded and saved locally by the client.
  162. // See `DirOptions`.
  163. Attachments = router.Attachments
  164. // Dir implements FileSystem using the native file system restricted to a
  165. // specific directory tree, can be passed to the `FileServer` function
  166. // and `HandleDir` method. It's an alias of `http.Dir`.
  167. Dir = http.Dir
  168. // ExecutionRules gives control to the execution of the route handlers outside of the handlers themselves.
  169. // Usage:
  170. // Party#SetExecutionRules(ExecutionRules {
  171. // Done: ExecutionOptions{Force: true},
  172. // })
  173. //
  174. // See `core/router/Party#SetExecutionRules` for more.
  175. // Example: https://github.com/kataras/iris/tree/main/_examples/mvc/middleware/without-ctx-next
  176. ExecutionRules = router.ExecutionRules
  177. // ExecutionOptions is a set of default behaviors that can be changed in order to customize the execution flow of the routes' handlers with ease.
  178. //
  179. // See `ExecutionRules` and `core/router/Party#SetExecutionRules` for more.
  180. ExecutionOptions = router.ExecutionOptions
  181. // CookieOption is the type of function that is accepted on
  182. // context's methods like `SetCookieKV`, `RemoveCookie` and `SetCookie`
  183. // as their (last) variadic input argument to amend the end cookie's form.
  184. //
  185. // Any custom or builtin `CookieOption` is valid,
  186. // see `CookiePath`, `CookieCleanPath`, `CookieExpires` and `CookieHTTPOnly` for more.
  187. //
  188. // An alias for the `context.CookieOption`.
  189. CookieOption = context.CookieOption
  190. // Cookie is a type alias for the standard net/http Cookie struct type.
  191. // See `Context.SetCookie`.
  192. Cookie = http.Cookie
  193. // N is a struct which can be passed on the `Context.Negotiate` method.
  194. // It contains fields which should be filled based on the `Context.Negotiation()`
  195. // server side values. If no matched mime then its "Other" field will be sent,
  196. // which should be a string or []byte.
  197. // It completes the `context/context.ContentSelector` interface.
  198. //
  199. // An alias for the `context.N`.
  200. N = context.N
  201. // Locale describes the i18n locale.
  202. // An alias for the `context.Locale`.
  203. Locale = context.Locale
  204. // ErrPrivate if provided then the error saved in context
  205. // should NOT be visible to the client no matter what.
  206. // An alias for the `context.ErrPrivate`.
  207. ErrPrivate = context.ErrPrivate
  208. )
  209. // Constants for input argument at `router.RouteRegisterRule`.
  210. // See `Party#SetRegisterRule`.
  211. const (
  212. // RouteOverride replaces an existing route with the new one, the default rule.
  213. RouteOverride = router.RouteOverride
  214. // RouteSkip keeps the original route and skips the new one.
  215. RouteSkip = router.RouteSkip
  216. // RouteError log when a route already exists, shown after the `Build` state,
  217. // server never starts.
  218. RouteError = router.RouteError
  219. // RouteOverlap will overlap the new route to the previous one.
  220. // If the route stopped and its response can be reset then the new route will be execute.
  221. RouteOverlap = router.RouteOverlap
  222. )
  223. // Contains the enum values of the `Context.GetReferrer()` method,
  224. // shortcuts of the context subpackage.
  225. const (
  226. ReferrerInvalid = context.ReferrerInvalid
  227. ReferrerIndirect = context.ReferrerIndirect
  228. ReferrerDirect = context.ReferrerDirect
  229. ReferrerEmail = context.ReferrerEmail
  230. ReferrerSearch = context.ReferrerSearch
  231. ReferrerSocial = context.ReferrerSocial
  232. ReferrerNotGoogleSearch = context.ReferrerNotGoogleSearch
  233. ReferrerGoogleOrganicSearch = context.ReferrerGoogleOrganicSearch
  234. ReferrerGoogleAdwords = context.ReferrerGoogleAdwords
  235. )
  236. // NoLayout to disable layout for a particular template file
  237. // A shortcut for the `view#NoLayout`.
  238. const NoLayout = view.NoLayout
  239. var (
  240. // HTML view engine.
  241. // Shortcut of the view.HTML.
  242. HTML = view.HTML
  243. // Blocks view engine.
  244. // Can be used as a faster alternative of the HTML engine.
  245. // Shortcut of the view.Blocks.
  246. Blocks = view.Blocks
  247. // Django view engine.
  248. // Shortcut of the view.Django.
  249. Django = view.Django
  250. // Handlebars view engine.
  251. // Shortcut of the view.Handlebars.
  252. Handlebars = view.Handlebars
  253. // Pug view engine.
  254. // Shortcut of the view.Pug.
  255. Pug = view.Pug
  256. // Jet view engine.
  257. // Shortcut of the view.Jet.
  258. Jet = view.Jet
  259. // Ace view engine.
  260. // Shortcut of the view.Ace.
  261. Ace = view.Ace
  262. )
  263. type (
  264. // ErrViewNotExist reports whether a template was not found in the parsed templates tree.
  265. ErrViewNotExist = context.ErrViewNotExist
  266. // FallbackViewFunc is a function that can be registered
  267. // to handle view fallbacks. It accepts the Context and
  268. // a special error which contains information about the previous template error.
  269. // It implements the FallbackViewProvider interface.
  270. //
  271. // See `Context.View` method.
  272. FallbackViewFunc = context.FallbackViewFunc
  273. // FallbackView is a helper to register a single template filename as a fallback
  274. // when the provided tempate filename was not found.
  275. FallbackView = context.FallbackView
  276. // FallbackViewLayout is a helper to register a single template filename as a fallback
  277. // layout when the provided layout filename was not found.
  278. FallbackViewLayout = context.FallbackViewLayout
  279. )
  280. // Component returns a new Handler which can be registered as a main handler for a route.
  281. // It's a shortcut handler that renders the given component as HTML through Context.RenderComponent.
  282. func Component(component context.Component) Handler {
  283. return func(ctx Context) {
  284. ctx.RenderComponent(component)
  285. }
  286. }
  287. // PrefixDir returns a new FileSystem that opens files
  288. // by adding the given "prefix" to the directory tree of "fs".
  289. //
  290. // Useful when having templates and static files in the same
  291. // bindata AssetFile method. This way you can select
  292. // which one to serve as static files and what for templates.
  293. // All view engines have a `RootDir` method for that reason too
  294. // but alternatively, you can wrap the given file system with this `PrefixDir`.
  295. //
  296. // Example: https://github.com/kataras/iris/blob/main/_examples/file-server/single-page-application/embedded-single-page-application/main.go
  297. func PrefixDir(prefix string, fs http.FileSystem) http.FileSystem {
  298. return &prefixedDir{prefix, fs}
  299. }
  300. // PrefixFS same as "PrefixDir" but for `fs.FS` type.
  301. func PrefixFS(fileSystem fs.FS, dir string) (fs.FS, error) {
  302. return fs.Sub(fileSystem, dir)
  303. }
  304. type prefixedDir struct {
  305. prefix string
  306. fs http.FileSystem
  307. }
  308. func (p *prefixedDir) Open(name string) (http.File, error) {
  309. name = path.Join(p.prefix, name)
  310. return p.fs.Open(name)
  311. }
  312. type partyConfiguratorMiddleware struct {
  313. handlers []Handler
  314. }
  315. func (p *partyConfiguratorMiddleware) Configure(r Party) {
  316. r.Use(p.handlers...)
  317. }
  318. // ConfigureMiddleware is a PartyConfigurator which can be used
  319. // as a shortcut to add middlewares on Party.PartyConfigure("/path", WithMiddleware(handler), new(example.API)).
  320. func ConfigureMiddleware(handlers ...Handler) router.PartyConfigurator {
  321. return &partyConfiguratorMiddleware{handlers: handlers}
  322. }
  323. // Compression is a middleware which enables
  324. // writing and reading using the best offered compression.
  325. // Usage:
  326. // app.Use (for matched routes)
  327. // app.UseRouter (for both matched and 404s or other HTTP errors).
  328. func Compression(ctx Context) {
  329. ctx.CompressWriter(true)
  330. ctx.CompressReader(true)
  331. ctx.Next()
  332. }
  333. var (
  334. // AllowQuerySemicolons returns a middleware that serves requests by converting any
  335. // unescaped semicolons(;) in the URL query to ampersands(&).
  336. //
  337. // This restores the pre-Go 1.17 behavior of splitting query parameters on both
  338. // semicolons and ampersands.
  339. // (See golang.org/issue/25192 and https://github.com/kataras/iris/issues/1875).
  340. // Note that this behavior doesn't match that of many proxies,
  341. // and the mismatch can lead to security issues.
  342. //
  343. // AllowQuerySemicolons should be invoked before any Context read query or
  344. // form methods are called.
  345. //
  346. // To skip HTTP Server logging for this type of warning:
  347. // app.Listen/Run(..., iris.WithoutServerError(iris.ErrURLQuerySemicolon)).
  348. AllowQuerySemicolons = func(ctx Context) {
  349. // clopy of net/http.AllowQuerySemicolons.
  350. r := ctx.Request()
  351. if s := r.URL.RawQuery; strings.Contains(s, ";") {
  352. r2 := new(http.Request)
  353. *r2 = *r
  354. r2.URL = new(url.URL)
  355. *r2.URL = *r.URL
  356. r2.URL.RawQuery = strings.ReplaceAll(s, ";", "&")
  357. ctx.ResetRequest(r2)
  358. }
  359. ctx.Next()
  360. }
  361. // MatchImagesAssets is a simple regex expression
  362. // that can be passed to the DirOptions.Cache.CompressIgnore field
  363. // in order to skip compression on already-compressed file types
  364. // such as images and pdf.
  365. MatchImagesAssets = regexp.MustCompile("((.*).pdf|(.*).jpg|(.*).jpeg|(.*).gif|(.*).tif|(.*).tiff)$")
  366. // MatchCommonAssets is a simple regex expression which
  367. // can be used on `DirOptions.PushTargetsRegexp`.
  368. // It will match and Push
  369. // all available js, css, font and media files.
  370. // Ideal for Single Page Applications.
  371. MatchCommonAssets = regexp.MustCompile("((.*).js|(.*).css|(.*).ico|(.*).png|(.*).ttf|(.*).svg|(.*).webp|(.*).gif)$")
  372. )
  373. var (
  374. // RegisterOnInterrupt registers a global function to call when CTRL+C/CMD+C pressed or a unix kill command received.
  375. //
  376. // A shortcut for the `host#RegisterOnInterrupt`.
  377. RegisterOnInterrupt = host.RegisterOnInterrupt
  378. // LimitRequestBodySize is a middleware which sets a request body size limit
  379. // for all next handlers in the chain.
  380. //
  381. // A shortcut for the `context#LimitRequestBodySize`.
  382. LimitRequestBodySize = context.LimitRequestBodySize
  383. // NewConditionalHandler returns a single Handler which can be registered
  384. // as a middleware.
  385. // Filter is just a type of Handler which returns a boolean.
  386. // Handlers here should act like middleware, they should contain `ctx.Next` to proceed
  387. // to the next handler of the chain. Those "handlers" are registered to the per-request context.
  388. //
  389. //
  390. // It checks the "filter" and if passed then
  391. // it, correctly, executes the "handlers".
  392. //
  393. // If passed, this function makes sure that the Context's information
  394. // about its per-request handler chain based on the new "handlers" is always updated.
  395. //
  396. // If not passed, then simply the Next handler(if any) is executed and "handlers" are ignored.
  397. // Example can be found at: _examples/routing/conditional-chain.
  398. //
  399. // A shortcut for the `context#NewConditionalHandler`.
  400. NewConditionalHandler = context.NewConditionalHandler
  401. // FileServer returns a Handler which serves files from a specific system, phyisical, directory
  402. // or an embedded one.
  403. // The first parameter is the directory, relative to the executable program.
  404. // The second optional parameter is any optional settings that the caller can use.
  405. //
  406. // See `Party#HandleDir` too.
  407. // Examples can be found at: https://github.com/kataras/iris/tree/main/_examples/file-server
  408. // A shortcut for the `router.FileServer`.
  409. FileServer = router.FileServer
  410. // DirList is the default `DirOptions.DirList` field.
  411. // Read more at: `core/router.DirList`.
  412. DirList = router.DirList
  413. // DirListRich can be passed to `DirOptions.DirList` field
  414. // to override the default file listing appearance.
  415. // Read more at: `core/router.DirListRich`.
  416. DirListRich = router.DirListRich
  417. // StripPrefix returns a handler that serves HTTP requests
  418. // by removing the given prefix from the request URL's Path
  419. // and invoking the handler h. StripPrefix handles a
  420. // request for a path that doesn't begin with prefix by
  421. // replying with an HTTP 404 not found error.
  422. //
  423. // Usage:
  424. // fileserver := iris.FileServer("./static_files", DirOptions {...})
  425. // h := iris.StripPrefix("/static", fileserver)
  426. // app.Get("/static/{file:path}", h)
  427. // app.Head("/static/{file:path}", h)
  428. StripPrefix = router.StripPrefix
  429. // FromStd converts native http.Handler, http.HandlerFunc & func(w, r, next) to context.Handler.
  430. //
  431. // Supported form types:
  432. // .FromStd(h http.Handler)
  433. // .FromStd(func(w http.ResponseWriter, r *http.Request))
  434. // .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
  435. //
  436. // A shortcut for the `handlerconv#FromStd`.
  437. FromStd = handlerconv.FromStd
  438. // Cache is a middleware providing server-side cache functionalities
  439. // to the next handlers, can be used as: `app.Get("/", iris.Cache, aboutHandler)`.
  440. // It should be used after Static methods.
  441. // See `iris#Cache304` for an alternative, faster way.
  442. //
  443. // Examples can be found at: https://github.com/kataras/iris/tree/main/_examples/#caching
  444. Cache = cache.Handler
  445. // NoCache is a middleware which overrides the Cache-Control, Pragma and Expires headers
  446. // in order to disable the cache during the browser's back and forward feature.
  447. //
  448. // A good use of this middleware is on HTML routes; to refresh the page even on "back" and "forward" browser's arrow buttons.
  449. //
  450. // See `iris#StaticCache` for the opposite behavior.
  451. //
  452. // A shortcut of the `cache#NoCache`
  453. NoCache = cache.NoCache
  454. // StaticCache middleware for caching static files by sending the "Cache-Control" and "Expires" headers to the client.
  455. // It accepts a single input parameter, the "cacheDur", a time.Duration that it's used to calculate the expiration.
  456. //
  457. // If "cacheDur" <=0 then it returns the `NoCache` middleware instaed to disable the caching between browser's "back" and "forward" actions.
  458. //
  459. // Usage: `app.Use(iris.StaticCache(24 * time.Hour))` or `app.Use(iris.StaticCache(-1))`.
  460. // A middleware, which is a simple Handler can be called inside another handler as well, example:
  461. // cacheMiddleware := iris.StaticCache(...)
  462. // func(ctx iris.Context){
  463. // cacheMiddleware(ctx)
  464. // [...]
  465. // }
  466. //
  467. // A shortcut of the `cache#StaticCache`
  468. StaticCache = cache.StaticCache
  469. // Cache304 sends a `StatusNotModified` (304) whenever
  470. // the "If-Modified-Since" request header (time) is before the
  471. // time.Now() + expiresEvery (always compared to their UTC values).
  472. // Use this, which is a shortcut of the, `chache#Cache304` instead of the "github.com/kataras/iris/v12/cache" or iris.Cache
  473. // for better performance.
  474. // Clients that are compatible with the http RCF (all browsers are and tools like postman)
  475. // will handle the caching.
  476. // The only disadvantage of using that instead of server-side caching
  477. // is that this method will send a 304 status code instead of 200,
  478. // So, if you use it side by side with other micro services
  479. // you have to check for that status code as well for a valid response.
  480. //
  481. // Developers are free to extend this method's behavior
  482. // by watching system directories changes manually and use of the `ctx.WriteWithExpiration`
  483. // with a "modtime" based on the file modified date,
  484. // similar to the `HandleDir`(which sends status OK(200) and browser disk caching instead of 304).
  485. //
  486. // A shortcut of the `cache#Cache304`.
  487. Cache304 = cache.Cache304
  488. // CookieOverride is a CookieOption which overrides the cookie explicitly to the given "cookie".
  489. //
  490. // A shortcut for the `context#CookieOverride`.
  491. CookieOverride = context.CookieOverride
  492. // CookieDomain is a CookieOption which sets the cookie's Domain field.
  493. // If empty then the current domain is used.
  494. //
  495. // A shortcut for the `context#CookieDomain`.
  496. CookieDomain = context.CookieDomain
  497. // CookieAllowReclaim accepts the Context itself.
  498. // If set it will add the cookie to (on `CookieSet`, `CookieSetKV`, `CookieUpsert`)
  499. // or remove the cookie from (on `CookieRemove`) the Request object too.
  500. //
  501. // A shortcut for the `context#CookieAllowReclaim`.
  502. CookieAllowReclaim = context.CookieAllowReclaim
  503. // CookieAllowSubdomains set to the Cookie Options
  504. // in order to allow subdomains to have access to the cookies.
  505. // It sets the cookie's Domain field (if was empty) and
  506. // it also sets the cookie's SameSite to lax mode too.
  507. //
  508. // A shortcut for the `context#CookieAllowSubdomains`.
  509. CookieAllowSubdomains = context.CookieAllowSubdomains
  510. // CookieSameSite sets a same-site rule for cookies to set.
  511. // SameSite allows a server to define a cookie attribute making it impossible for
  512. // the browser to send this cookie along with cross-site requests. The main
  513. // goal is to mitigate the risk of cross-origin information leakage, and provide
  514. // some protection against cross-site request forgery attacks.
  515. //
  516. // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
  517. //
  518. // A shortcut for the `context#CookieSameSite`.
  519. CookieSameSite = context.CookieSameSite
  520. // CookieSecure sets the cookie's Secure option if the current request's
  521. // connection is using TLS. See `CookieHTTPOnly` too.
  522. //
  523. // A shortcut for the `context#CookieSecure`.
  524. CookieSecure = context.CookieSecure
  525. // CookieHTTPOnly is a `CookieOption`.
  526. // Use it to set the cookie's HttpOnly field to false or true.
  527. // HttpOnly field defaults to true for `RemoveCookie` and `SetCookieKV`.
  528. //
  529. // A shortcut for the `context#CookieHTTPOnly`.
  530. CookieHTTPOnly = context.CookieHTTPOnly
  531. // CookiePath is a `CookieOption`.
  532. // Use it to change the cookie's Path field.
  533. //
  534. // A shortcut for the `context#CookiePath`.
  535. CookiePath = context.CookiePath
  536. // CookieCleanPath is a `CookieOption`.
  537. // Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
  538. //
  539. // A shortcut for the `context#CookieCleanPath`.
  540. CookieCleanPath = context.CookieCleanPath
  541. // CookieExpires is a `CookieOption`.
  542. // Use it to change the cookie's Expires and MaxAge fields by passing the lifetime of the cookie.
  543. //
  544. // A shortcut for the `context#CookieExpires`.
  545. CookieExpires = context.CookieExpires
  546. // CookieEncoding accepts a value which implements `Encode` and `Decode` methods.
  547. // It calls its `Encode` on `Context.SetCookie, UpsertCookie, and SetCookieKV` methods.
  548. // And on `Context.GetCookie` method it calls its `Decode`.
  549. //
  550. // A shortcut for the `context#CookieEncoding`.
  551. CookieEncoding = context.CookieEncoding
  552. // IsErrEmptyJSON reports whether the given "err" is caused by a
  553. // Context.ReadJSON call when the request body
  554. // didn't start with { or it was totally empty.
  555. IsErrEmptyJSON = context.IsErrEmptyJSON
  556. // IsErrPath can be used at `context#ReadForm` and `context#ReadQuery`.
  557. // It reports whether the incoming error is type of `schema.ErrPath`,
  558. // which can be ignored when server allows unknown post values to be sent by the client.
  559. //
  560. // A shortcut for the `context#IsErrPath`.
  561. IsErrPath = context.IsErrPath
  562. // IsErrCanceled reports whether the "err" is caused by a cancellation or timeout.
  563. //
  564. // A shortcut for the `context#IsErrCanceled`.
  565. IsErrCanceled = context.IsErrCanceled
  566. // ErrEmptyForm is the type error which API users can make use of
  567. // to check if a form was empty on `Context.ReadForm`.
  568. //
  569. // A shortcut for the `context#ErrEmptyForm`.
  570. ErrEmptyForm = context.ErrEmptyForm
  571. // ErrEmptyFormField reports whether if form value is empty.
  572. // An alias of `context.ErrEmptyFormField`.
  573. ErrEmptyFormField = context.ErrEmptyFormField
  574. // ErrNotFound reports whether a key was not found, useful
  575. // on post data, versioning feature and others.
  576. // An alias of `context.ErrNotFound`.
  577. ErrNotFound = context.ErrNotFound
  578. // NewProblem returns a new Problem.
  579. // Head over to the `Problem` type godoc for more.
  580. //
  581. // A shortcut for the `context#NewProblem`.
  582. NewProblem = context.NewProblem
  583. // XMLMap wraps a map[string]interface{} to compatible xml marshaler,
  584. // in order to be able to render maps as XML on the `Context.XML` method.
  585. //
  586. // Example: `Context.XML(XMLMap("Root", map[string]interface{}{...})`.
  587. //
  588. // A shortcut for the `context#XMLMap`.
  589. XMLMap = context.XMLMap
  590. // ErrStopExecution if returned from a hero middleware or a request-scope dependency
  591. // stops the handler's execution, see _examples/dependency-injection/basic/middleware.
  592. ErrStopExecution = hero.ErrStopExecution
  593. // ErrHijackNotSupported is returned by the Hijack method to
  594. // indicate that Hijack feature is not available.
  595. //
  596. // A shortcut for the `context#ErrHijackNotSupported`.
  597. ErrHijackNotSupported = context.ErrHijackNotSupported
  598. // ErrPushNotSupported is returned by the Push method to
  599. // indicate that HTTP/2 Push support is not available.
  600. //
  601. // A shortcut for the `context#ErrPushNotSupported`.
  602. ErrPushNotSupported = context.ErrPushNotSupported
  603. // PrivateError accepts an error and returns a wrapped private one.
  604. // A shortcut for the `context#PrivateError` function.
  605. PrivateError = context.PrivateError
  606. // TrimParamFilePart is a middleware which trims any last part after a dot (.) character
  607. // of the current route's dynamic path parameters.
  608. // A shortcut for the `context#TrimParamFilePart` function.
  609. TrimParamFilePart Handler = context.TrimParamFilePart
  610. )
  611. // HTTP Methods copied from `net/http`.
  612. const (
  613. MethodGet = http.MethodGet
  614. MethodPost = http.MethodPost
  615. MethodPut = http.MethodPut
  616. MethodDelete = http.MethodDelete
  617. MethodConnect = http.MethodConnect
  618. MethodHead = http.MethodHead
  619. MethodPatch = http.MethodPatch
  620. MethodOptions = http.MethodOptions
  621. MethodTrace = http.MethodTrace
  622. // MethodNone is an iris-specific "virtual" method
  623. // to store the "offline" routes.
  624. MethodNone = router.MethodNone
  625. )
  626. // HTTP status codes as registered with IANA.
  627. // See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml.
  628. // Raw Copy from the future(tip) net/http std package in order to recude the import path of "net/http" for the users.
  629. const (
  630. StatusContinue = http.StatusContinue // RFC 7231, 6.2.1
  631. StatusSwitchingProtocols = http.StatusSwitchingProtocols // RFC 7231, 6.2.2
  632. StatusProcessing = http.StatusProcessing // RFC 2518, 10.1
  633. StatusEarlyHints = http.StatusEarlyHints // RFC 8297
  634. StatusOK = http.StatusOK // RFC 7231, 6.3.1
  635. StatusCreated = http.StatusCreated // RFC 7231, 6.3.2
  636. StatusAccepted = http.StatusAccepted // RFC 7231, 6.3.3
  637. StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo // RFC 7231, 6.3.4
  638. StatusNoContent = http.StatusNoContent // RFC 7231, 6.3.5
  639. StatusResetContent = http.StatusResetContent // RFC 7231, 6.3.6
  640. StatusPartialContent = http.StatusPartialContent // RFC 7233, 4.1
  641. StatusMultiStatus = http.StatusMultiStatus // RFC 4918, 11.1
  642. StatusAlreadyReported = http.StatusAlreadyReported // RFC 5842, 7.1
  643. StatusIMUsed = http.StatusIMUsed // RFC 3229, 10.4.1
  644. StatusMultipleChoices = http.StatusMultipleChoices // RFC 7231, 6.4.1
  645. StatusMovedPermanently = http.StatusMovedPermanently // RFC 7231, 6.4.2
  646. StatusFound = http.StatusFound // RFC 7231, 6.4.3
  647. StatusSeeOther = http.StatusSeeOther // RFC 7231, 6.4.4
  648. StatusNotModified = http.StatusNotModified // RFC 7232, 4.1
  649. StatusUseProxy = http.StatusUseProxy // RFC 7231, 6.4.5
  650. _ = 306 // RFC 7231, 6.4.6 (Unused)
  651. StatusTemporaryRedirect = http.StatusTemporaryRedirect // RFC 7231, 6.4.7
  652. StatusPermanentRedirect = http.StatusPermanentRedirect // RFC 7538, 3
  653. StatusBadRequest = http.StatusBadRequest // RFC 7231, 6.5.1
  654. StatusUnauthorized = http.StatusUnauthorized // RFC 7235, 3.1
  655. StatusPaymentRequired = http.StatusPaymentRequired // RFC 7231, 6.5.2
  656. StatusForbidden = http.StatusForbidden // RFC 7231, 6.5.3
  657. StatusNotFound = http.StatusNotFound // RFC 7231, 6.5.4
  658. StatusMethodNotAllowed = http.StatusMethodNotAllowed // RFC 7231, 6.5.5
  659. StatusNotAcceptable = http.StatusNotAcceptable // RFC 7231, 6.5.6
  660. StatusProxyAuthRequired = http.StatusProxyAuthRequired // RFC 7235, 3.2
  661. StatusRequestTimeout = http.StatusRequestTimeout // RFC 7231, 6.5.7
  662. StatusConflict = http.StatusConflict // RFC 7231, 6.5.8
  663. StatusGone = http.StatusGone // RFC 7231, 6.5.9
  664. StatusLengthRequired = http.StatusLengthRequired // RFC 7231, 6.5.10
  665. StatusPreconditionFailed = http.StatusPreconditionFailed // RFC 7232, 4.2
  666. StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge // RFC 7231, 6.5.11
  667. StatusRequestURITooLong = http.StatusRequestURITooLong // RFC 7231, 6.5.12
  668. StatusUnsupportedMediaType = http.StatusUnsupportedMediaType // RFC 7231, 6.5.13
  669. StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable // RFC 7233, 4.4
  670. StatusExpectationFailed = http.StatusExpectationFailed // RFC 7231, 6.5.14
  671. StatusTeapot = http.StatusTeapot // RFC 7168, 2.3.3
  672. StatusMisdirectedRequest = http.StatusMisdirectedRequest // RFC 7540, 9.1.2
  673. StatusUnprocessableEntity = http.StatusUnprocessableEntity // RFC 4918, 11.2
  674. StatusLocked = http.StatusLocked // RFC 4918, 11.3
  675. StatusFailedDependency = http.StatusFailedDependency // RFC 4918, 11.4
  676. StatusTooEarly = http.StatusTooEarly // RFC 8470, 5.2.
  677. StatusUpgradeRequired = http.StatusUpgradeRequired // RFC 7231, 6.5.15
  678. StatusPreconditionRequired = http.StatusPreconditionRequired // RFC 6585, 3
  679. StatusTooManyRequests = http.StatusTooManyRequests // RFC 6585, 4
  680. StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge // RFC 6585, 5
  681. StatusUnavailableForLegalReasons = http.StatusUnavailableForLegalReasons // RFC 7725, 3
  682. // Unofficial Client Errors.
  683. StatusPageExpired = context.StatusPageExpired
  684. StatusBlockedByWindowsParentalControls = context.StatusBlockedByWindowsParentalControls
  685. StatusInvalidToken = context.StatusInvalidToken
  686. StatusTokenRequired = context.StatusTokenRequired
  687. //
  688. StatusInternalServerError = http.StatusInternalServerError // RFC 7231, 6.6.1
  689. StatusNotImplemented = http.StatusNotImplemented // RFC 7231, 6.6.2
  690. StatusBadGateway = http.StatusBadGateway // RFC 7231, 6.6.3
  691. StatusServiceUnavailable = http.StatusServiceUnavailable // RFC 7231, 6.6.4
  692. StatusGatewayTimeout = http.StatusGatewayTimeout // RFC 7231, 6.6.5
  693. StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported // RFC 7231, 6.6.6
  694. StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates // RFC 2295, 8.1
  695. StatusInsufficientStorage = http.StatusInsufficientStorage // RFC 4918, 11.5
  696. StatusLoopDetected = http.StatusLoopDetected // RFC 5842, 7.2
  697. StatusNotExtended = http.StatusNotExtended // RFC 2774, 7
  698. StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired // RFC 6585, 6
  699. // Unofficial Server Errors.
  700. StatusBandwidthLimitExceeded = context.StatusBandwidthLimitExceeded
  701. StatusInvalidSSLCertificate = context.StatusInvalidSSLCertificate
  702. StatusSiteOverloaded = context.StatusSiteOverloaded
  703. StatusSiteFrozen = context.StatusSiteFrozen
  704. StatusNetworkReadTimeout = context.StatusNetworkReadTimeout
  705. )
  706. var (
  707. // StatusText returns a text for the HTTP status code. It returns the empty
  708. // string if the code is unknown.
  709. //
  710. // Shortcut for core/router#StatusText.
  711. StatusText = context.StatusText
  712. // RegisterMethods adds custom http methods to the "AllMethods" list.
  713. // Use it on initialization of your program.
  714. //
  715. // Shortcut for core/router#RegisterMethods.
  716. RegisterMethods = router.RegisterMethods
  717. // WebDAVMethods contains a list of WebDAV HTTP Verbs.
  718. // Register using RegiterMethods package-level function or
  719. // through HandleMany party-level method.
  720. WebDAVMethods = []string{
  721. MethodGet,
  722. MethodHead,
  723. MethodPatch,
  724. MethodPut,
  725. MethodPost,
  726. MethodDelete,
  727. MethodOptions,
  728. MethodConnect,
  729. MethodTrace,
  730. "MKCOL",
  731. "COPY",
  732. "MOVE",
  733. "LOCK",
  734. "UNLOCK",
  735. "PROPFIND",
  736. "PROPPATCH",
  737. "LINK",
  738. "UNLINK",
  739. "PURGE",
  740. "VIEW",
  741. }
  742. )
  743. var globalPatches = &GlobalPatches{
  744. contextPatches: &ContextPatches{
  745. writers: &ContextWriterPatches{},
  746. },
  747. }
  748. // GlobalPatches is a singleton features a uniform way to apply global/package-level modifications.
  749. //
  750. // See the `Patches` package-level function.
  751. type GlobalPatches struct {
  752. contextPatches *ContextPatches
  753. }
  754. // Patches returns the singleton of GlobalPatches, an easy way to modify
  755. // global(package-level) configuration for Iris applications.
  756. //
  757. // See its `Context` method.
  758. //
  759. // Example: https://github.com/kataras/iris/blob/main/_examples/response-writer/json-third-party/main.go
  760. func Patches() *GlobalPatches { // singleton.
  761. return globalPatches
  762. }
  763. // Context returns the available context patches.
  764. func (p *GlobalPatches) Context() *ContextPatches {
  765. return p.contextPatches
  766. }
  767. // ContextPatches contains the available global Iris context modifications.
  768. type ContextPatches struct {
  769. writers *ContextWriterPatches
  770. }
  771. // Writers returns the available global Iris context modifications for REST writers.
  772. func (cp *ContextPatches) Writers() *ContextWriterPatches {
  773. return cp.writers
  774. }
  775. // GetDomain modifies the way a domain is fetched from `Context#Domain` method,
  776. // which is used on subdomain redirect feature, i18n's language cookie for subdomain sharing
  777. // and the rewrite middleware.
  778. func (cp *ContextPatches) GetDomain(patchFunc func(hostport string) string) {
  779. context.GetDomain = patchFunc
  780. }
  781. // SetCookieKVExpiration modifies the default cookie expiration time on `Context#SetCookieKV` method.
  782. func (cp *ContextPatches) SetCookieKVExpiration(patch time.Duration) {
  783. context.SetCookieKVExpiration = patch
  784. }
  785. // ResolveHTTPFS modifies the default way to resolve a filesystem by any type of value.
  786. // It affects the Application's API Builder's `HandleDir` method.
  787. func (cp *ContextPatches) ResolveHTTPFS(patchFunc func(fsOrDir interface{}) http.FileSystem) {
  788. context.ResolveHTTPFS = patchFunc
  789. }
  790. // ResolveHTTPFS modifies the default way to resolve a filesystem by any type of value.
  791. // It affects the view engine's filesystem resolver.
  792. func (cp *ContextPatches) ResolveFS(patchFunc func(fsOrDir interface{}) fs.FS) {
  793. context.ResolveFS = patchFunc
  794. }
  795. // ContextWriterPatches features the context's writers patches.
  796. type ContextWriterPatches struct{}
  797. // JSON sets a custom function which runs and overrides the default behavior of the `Context#JSON` method.
  798. func (cwp *ContextWriterPatches) JSON(patchFunc func(ctx Context, v interface{}, options *JSON) error) {
  799. context.WriteJSON = patchFunc
  800. }
  801. // JSONP sets a custom function which runs and overrides the default behavior of the `Context#JSONP` method.
  802. func (cwp *ContextWriterPatches) JSONP(patchFunc func(ctx Context, v interface{}, options *JSONP) error) {
  803. context.WriteJSONP = patchFunc
  804. }
  805. // XML sets a custom function which runs and overrides the default behavior of the `Context#XML` method.
  806. func (cwp *ContextWriterPatches) XML(patchFunc func(ctx Context, v interface{}, options *XML) error) {
  807. context.WriteXML = patchFunc
  808. }
  809. // Markdown sets a custom function which runs and overrides the default behavior of the `Context#Markdown` method.
  810. func (cwp *ContextWriterPatches) Markdown(patchFunc func(ctx Context, v []byte, options *Markdown) error) {
  811. context.WriteMarkdown = patchFunc
  812. }
  813. // YAML sets a custom function which runs and overrides the default behavior of the `Context#YAML` method.
  814. func (cwp *ContextWriterPatches) YAML(patchFunc func(ctx Context, v interface{}, indentSpace int) error) {
  815. context.WriteYAML = patchFunc
  816. }
  817. // Singleton is a structure which can be used as an embedded field on
  818. // struct/controllers that should be marked as singletons on `PartyConfigure` or `MVC` Applications.
  819. type Singleton struct{}
  820. // Singleton returns true as this controller is a singleton.
  821. func (c Singleton) Singleton() bool { return true }