aliases.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. // PrefixDir returns a new FileSystem that opens files
  281. // by adding the given "prefix" to the directory tree of "fs".
  282. //
  283. // Useful when having templates and static files in the same
  284. // bindata AssetFile method. This way you can select
  285. // which one to serve as static files and what for templates.
  286. // All view engines have a `RootDir` method for that reason too
  287. // but alternatively, you can wrap the given file system with this `PrefixDir`.
  288. //
  289. // Example: https://github.com/kataras/iris/blob/main/_examples/file-server/single-page-application/embedded-single-page-application/main.go
  290. func PrefixDir(prefix string, fs http.FileSystem) http.FileSystem {
  291. return &prefixedDir{prefix, fs}
  292. }
  293. // PrefixFS same as "PrefixDir" but for `fs.FS` type.
  294. func PrefixFS(fileSystem fs.FS, dir string) (fs.FS, error) {
  295. return fs.Sub(fileSystem, dir)
  296. }
  297. type prefixedDir struct {
  298. prefix string
  299. fs http.FileSystem
  300. }
  301. func (p *prefixedDir) Open(name string) (http.File, error) {
  302. name = path.Join(p.prefix, name)
  303. return p.fs.Open(name)
  304. }
  305. type partyConfiguratorMiddleware struct {
  306. handlers []Handler
  307. }
  308. func (p *partyConfiguratorMiddleware) Configure(r Party) {
  309. r.Use(p.handlers...)
  310. }
  311. // ConfigureMiddleware is a PartyConfigurator which can be used
  312. // as a shortcut to add middlewares on Party.PartyConfigure("/path", WithMiddleware(handler), new(example.API)).
  313. func ConfigureMiddleware(handlers ...Handler) router.PartyConfigurator {
  314. return &partyConfiguratorMiddleware{handlers: handlers}
  315. }
  316. // Compression is a middleware which enables
  317. // writing and reading using the best offered compression.
  318. // Usage:
  319. // app.Use (for matched routes)
  320. // app.UseRouter (for both matched and 404s or other HTTP errors).
  321. func Compression(ctx Context) {
  322. ctx.CompressWriter(true)
  323. ctx.CompressReader(true)
  324. ctx.Next()
  325. }
  326. var (
  327. // AllowQuerySemicolons returns a middleware that serves requests by converting any
  328. // unescaped semicolons(;) in the URL query to ampersands(&).
  329. //
  330. // This restores the pre-Go 1.17 behavior of splitting query parameters on both
  331. // semicolons and ampersands.
  332. // (See golang.org/issue/25192 and https://github.com/kataras/iris/issues/1875).
  333. // Note that this behavior doesn't match that of many proxies,
  334. // and the mismatch can lead to security issues.
  335. //
  336. // AllowQuerySemicolons should be invoked before any Context read query or
  337. // form methods are called.
  338. //
  339. // To skip HTTP Server logging for this type of warning:
  340. // app.Listen/Run(..., iris.WithoutServerError(iris.ErrURLQuerySemicolon)).
  341. AllowQuerySemicolons = func(ctx Context) {
  342. // clopy of net/http.AllowQuerySemicolons.
  343. r := ctx.Request()
  344. if s := r.URL.RawQuery; strings.Contains(s, ";") {
  345. r2 := new(http.Request)
  346. *r2 = *r
  347. r2.URL = new(url.URL)
  348. *r2.URL = *r.URL
  349. r2.URL.RawQuery = strings.ReplaceAll(s, ";", "&")
  350. ctx.ResetRequest(r2)
  351. }
  352. ctx.Next()
  353. }
  354. // MatchImagesAssets is a simple regex expression
  355. // that can be passed to the DirOptions.Cache.CompressIgnore field
  356. // in order to skip compression on already-compressed file types
  357. // such as images and pdf.
  358. MatchImagesAssets = regexp.MustCompile("((.*).pdf|(.*).jpg|(.*).jpeg|(.*).gif|(.*).tif|(.*).tiff)$")
  359. // MatchCommonAssets is a simple regex expression which
  360. // can be used on `DirOptions.PushTargetsRegexp`.
  361. // It will match and Push
  362. // all available js, css, font and media files.
  363. // Ideal for Single Page Applications.
  364. MatchCommonAssets = regexp.MustCompile("((.*).js|(.*).css|(.*).ico|(.*).png|(.*).ttf|(.*).svg|(.*).webp|(.*).gif)$")
  365. )
  366. var (
  367. // RegisterOnInterrupt registers a global function to call when CTRL+C/CMD+C pressed or a unix kill command received.
  368. //
  369. // A shortcut for the `host#RegisterOnInterrupt`.
  370. RegisterOnInterrupt = host.RegisterOnInterrupt
  371. // LimitRequestBodySize is a middleware which sets a request body size limit
  372. // for all next handlers in the chain.
  373. //
  374. // A shortcut for the `context#LimitRequestBodySize`.
  375. LimitRequestBodySize = context.LimitRequestBodySize
  376. // NewConditionalHandler returns a single Handler which can be registered
  377. // as a middleware.
  378. // Filter is just a type of Handler which returns a boolean.
  379. // Handlers here should act like middleware, they should contain `ctx.Next` to proceed
  380. // to the next handler of the chain. Those "handlers" are registered to the per-request context.
  381. //
  382. //
  383. // It checks the "filter" and if passed then
  384. // it, correctly, executes the "handlers".
  385. //
  386. // If passed, this function makes sure that the Context's information
  387. // about its per-request handler chain based on the new "handlers" is always updated.
  388. //
  389. // If not passed, then simply the Next handler(if any) is executed and "handlers" are ignored.
  390. // Example can be found at: _examples/routing/conditional-chain.
  391. //
  392. // A shortcut for the `context#NewConditionalHandler`.
  393. NewConditionalHandler = context.NewConditionalHandler
  394. // FileServer returns a Handler which serves files from a specific system, phyisical, directory
  395. // or an embedded one.
  396. // The first parameter is the directory, relative to the executable program.
  397. // The second optional parameter is any optional settings that the caller can use.
  398. //
  399. // See `Party#HandleDir` too.
  400. // Examples can be found at: https://github.com/kataras/iris/tree/main/_examples/file-server
  401. // A shortcut for the `router.FileServer`.
  402. FileServer = router.FileServer
  403. // DirList is the default `DirOptions.DirList` field.
  404. // Read more at: `core/router.DirList`.
  405. DirList = router.DirList
  406. // DirListRich can be passed to `DirOptions.DirList` field
  407. // to override the default file listing appearance.
  408. // Read more at: `core/router.DirListRich`.
  409. DirListRich = router.DirListRich
  410. // StripPrefix returns a handler that serves HTTP requests
  411. // by removing the given prefix from the request URL's Path
  412. // and invoking the handler h. StripPrefix handles a
  413. // request for a path that doesn't begin with prefix by
  414. // replying with an HTTP 404 not found error.
  415. //
  416. // Usage:
  417. // fileserver := iris.FileServer("./static_files", DirOptions {...})
  418. // h := iris.StripPrefix("/static", fileserver)
  419. // app.Get("/static/{file:path}", h)
  420. // app.Head("/static/{file:path}", h)
  421. StripPrefix = router.StripPrefix
  422. // FromStd converts native http.Handler, http.HandlerFunc & func(w, r, next) to context.Handler.
  423. //
  424. // Supported form types:
  425. // .FromStd(h http.Handler)
  426. // .FromStd(func(w http.ResponseWriter, r *http.Request))
  427. // .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
  428. //
  429. // A shortcut for the `handlerconv#FromStd`.
  430. FromStd = handlerconv.FromStd
  431. // Cache is a middleware providing server-side cache functionalities
  432. // to the next handlers, can be used as: `app.Get("/", iris.Cache, aboutHandler)`.
  433. // It should be used after Static methods.
  434. // See `iris#Cache304` for an alternative, faster way.
  435. //
  436. // Examples can be found at: https://github.com/kataras/iris/tree/main/_examples/#caching
  437. Cache = cache.Handler
  438. // NoCache is a middleware which overrides the Cache-Control, Pragma and Expires headers
  439. // in order to disable the cache during the browser's back and forward feature.
  440. //
  441. // A good use of this middleware is on HTML routes; to refresh the page even on "back" and "forward" browser's arrow buttons.
  442. //
  443. // See `iris#StaticCache` for the opposite behavior.
  444. //
  445. // A shortcut of the `cache#NoCache`
  446. NoCache = cache.NoCache
  447. // StaticCache middleware for caching static files by sending the "Cache-Control" and "Expires" headers to the client.
  448. // It accepts a single input parameter, the "cacheDur", a time.Duration that it's used to calculate the expiration.
  449. //
  450. // If "cacheDur" <=0 then it returns the `NoCache` middleware instaed to disable the caching between browser's "back" and "forward" actions.
  451. //
  452. // Usage: `app.Use(iris.StaticCache(24 * time.Hour))` or `app.Use(iris.StaticCache(-1))`.
  453. // A middleware, which is a simple Handler can be called inside another handler as well, example:
  454. // cacheMiddleware := iris.StaticCache(...)
  455. // func(ctx iris.Context){
  456. // cacheMiddleware(ctx)
  457. // [...]
  458. // }
  459. //
  460. // A shortcut of the `cache#StaticCache`
  461. StaticCache = cache.StaticCache
  462. // Cache304 sends a `StatusNotModified` (304) whenever
  463. // the "If-Modified-Since" request header (time) is before the
  464. // time.Now() + expiresEvery (always compared to their UTC values).
  465. // Use this, which is a shortcut of the, `chache#Cache304` instead of the "github.com/kataras/iris/v12/cache" or iris.Cache
  466. // for better performance.
  467. // Clients that are compatible with the http RCF (all browsers are and tools like postman)
  468. // will handle the caching.
  469. // The only disadvantage of using that instead of server-side caching
  470. // is that this method will send a 304 status code instead of 200,
  471. // So, if you use it side by side with other micro services
  472. // you have to check for that status code as well for a valid response.
  473. //
  474. // Developers are free to extend this method's behavior
  475. // by watching system directories changes manually and use of the `ctx.WriteWithExpiration`
  476. // with a "modtime" based on the file modified date,
  477. // similar to the `HandleDir`(which sends status OK(200) and browser disk caching instead of 304).
  478. //
  479. // A shortcut of the `cache#Cache304`.
  480. Cache304 = cache.Cache304
  481. // CookieAllowReclaim accepts the Context itself.
  482. // If set it will add the cookie to (on `CookieSet`, `CookieSetKV`, `CookieUpsert`)
  483. // or remove the cookie from (on `CookieRemove`) the Request object too.
  484. //
  485. // A shortcut for the `context#CookieAllowReclaim`.
  486. CookieAllowReclaim = context.CookieAllowReclaim
  487. // CookieAllowSubdomains set to the Cookie Options
  488. // in order to allow subdomains to have access to the cookies.
  489. // It sets the cookie's Domain field (if was empty) and
  490. // it also sets the cookie's SameSite to lax mode too.
  491. //
  492. // A shortcut for the `context#CookieAllowSubdomains`.
  493. CookieAllowSubdomains = context.CookieAllowSubdomains
  494. // CookieSameSite sets a same-site rule for cookies to set.
  495. // SameSite allows a server to define a cookie attribute making it impossible for
  496. // the browser to send this cookie along with cross-site requests. The main
  497. // goal is to mitigate the risk of cross-origin information leakage, and provide
  498. // some protection against cross-site request forgery attacks.
  499. //
  500. // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
  501. //
  502. // A shortcut for the `context#CookieSameSite`.
  503. CookieSameSite = context.CookieSameSite
  504. // CookieSecure sets the cookie's Secure option if the current request's
  505. // connection is using TLS. See `CookieHTTPOnly` too.
  506. //
  507. // A shortcut for the `context#CookieSecure`.
  508. CookieSecure = context.CookieSecure
  509. // CookieHTTPOnly is a `CookieOption`.
  510. // Use it to set the cookie's HttpOnly field to false or true.
  511. // HttpOnly field defaults to true for `RemoveCookie` and `SetCookieKV`.
  512. //
  513. // A shortcut for the `context#CookieHTTPOnly`.
  514. CookieHTTPOnly = context.CookieHTTPOnly
  515. // CookiePath is a `CookieOption`.
  516. // Use it to change the cookie's Path field.
  517. //
  518. // A shortcut for the `context#CookiePath`.
  519. CookiePath = context.CookiePath
  520. // CookieCleanPath is a `CookieOption`.
  521. // Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
  522. //
  523. // A shortcut for the `context#CookieCleanPath`.
  524. CookieCleanPath = context.CookieCleanPath
  525. // CookieExpires is a `CookieOption`.
  526. // Use it to change the cookie's Expires and MaxAge fields by passing the lifetime of the cookie.
  527. //
  528. // A shortcut for the `context#CookieExpires`.
  529. CookieExpires = context.CookieExpires
  530. // CookieEncoding accepts a value which implements `Encode` and `Decode` methods.
  531. // It calls its `Encode` on `Context.SetCookie, UpsertCookie, and SetCookieKV` methods.
  532. // And on `Context.GetCookie` method it calls its `Decode`.
  533. //
  534. // A shortcut for the `context#CookieEncoding`.
  535. CookieEncoding = context.CookieEncoding
  536. // IsErrEmptyJSON reports whether the given "err" is caused by a
  537. // Context.ReadJSON call when the request body
  538. // didn't start with { or it was totally empty.
  539. IsErrEmptyJSON = context.IsErrEmptyJSON
  540. // IsErrPath can be used at `context#ReadForm` and `context#ReadQuery`.
  541. // It reports whether the incoming error is type of `schema.ErrPath`,
  542. // which can be ignored when server allows unknown post values to be sent by the client.
  543. //
  544. // A shortcut for the `context#IsErrPath`.
  545. IsErrPath = context.IsErrPath
  546. // IsErrCanceled reports whether the "err" is caused by a cancellation or timeout.
  547. //
  548. // A shortcut for the `context#IsErrCanceled`.
  549. IsErrCanceled = context.IsErrCanceled
  550. // ErrEmptyForm is the type error which API users can make use of
  551. // to check if a form was empty on `Context.ReadForm`.
  552. //
  553. // A shortcut for the `context#ErrEmptyForm`.
  554. ErrEmptyForm = context.ErrEmptyForm
  555. // ErrEmptyFormField reports whether if form value is empty.
  556. // An alias of `context.ErrEmptyFormField`.
  557. ErrEmptyFormField = context.ErrEmptyFormField
  558. // ErrNotFound reports whether a key was not found, useful
  559. // on post data, versioning feature and others.
  560. // An alias of `context.ErrNotFound`.
  561. ErrNotFound = context.ErrNotFound
  562. // NewProblem returns a new Problem.
  563. // Head over to the `Problem` type godoc for more.
  564. //
  565. // A shortcut for the `context#NewProblem`.
  566. NewProblem = context.NewProblem
  567. // XMLMap wraps a map[string]interface{} to compatible xml marshaler,
  568. // in order to be able to render maps as XML on the `Context.XML` method.
  569. //
  570. // Example: `Context.XML(XMLMap("Root", map[string]interface{}{...})`.
  571. //
  572. // A shortcut for the `context#XMLMap`.
  573. XMLMap = context.XMLMap
  574. // ErrStopExecution if returned from a hero middleware or a request-scope dependency
  575. // stops the handler's execution, see _examples/dependency-injection/basic/middleware.
  576. ErrStopExecution = hero.ErrStopExecution
  577. // ErrHijackNotSupported is returned by the Hijack method to
  578. // indicate that Hijack feature is not available.
  579. //
  580. // A shortcut for the `context#ErrHijackNotSupported`.
  581. ErrHijackNotSupported = context.ErrHijackNotSupported
  582. // ErrPushNotSupported is returned by the Push method to
  583. // indicate that HTTP/2 Push support is not available.
  584. //
  585. // A shortcut for the `context#ErrPushNotSupported`.
  586. ErrPushNotSupported = context.ErrPushNotSupported
  587. // PrivateError accepts an error and returns a wrapped private one.
  588. // A shortcut for the `context#PrivateError` function.
  589. PrivateError = context.PrivateError
  590. // TrimParamFilePart is a middleware which trims any last part after a dot (.) character
  591. // of the current route's dynamic path parameters.
  592. // A shortcut for the `context#TrimParamFilePart` function.
  593. TrimParamFilePart Handler = context.TrimParamFilePart
  594. )
  595. // HTTP Methods copied from `net/http`.
  596. const (
  597. MethodGet = http.MethodGet
  598. MethodPost = http.MethodPost
  599. MethodPut = http.MethodPut
  600. MethodDelete = http.MethodDelete
  601. MethodConnect = http.MethodConnect
  602. MethodHead = http.MethodHead
  603. MethodPatch = http.MethodPatch
  604. MethodOptions = http.MethodOptions
  605. MethodTrace = http.MethodTrace
  606. // MethodNone is an iris-specific "virtual" method
  607. // to store the "offline" routes.
  608. MethodNone = router.MethodNone
  609. )
  610. // HTTP status codes as registered with IANA.
  611. // See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml.
  612. // Raw Copy from the future(tip) net/http std package in order to recude the import path of "net/http" for the users.
  613. const (
  614. StatusContinue = http.StatusContinue // RFC 7231, 6.2.1
  615. StatusSwitchingProtocols = http.StatusSwitchingProtocols // RFC 7231, 6.2.2
  616. StatusProcessing = http.StatusProcessing // RFC 2518, 10.1
  617. StatusEarlyHints = http.StatusEarlyHints // RFC 8297
  618. StatusOK = http.StatusOK // RFC 7231, 6.3.1
  619. StatusCreated = http.StatusCreated // RFC 7231, 6.3.2
  620. StatusAccepted = http.StatusAccepted // RFC 7231, 6.3.3
  621. StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo // RFC 7231, 6.3.4
  622. StatusNoContent = http.StatusNoContent // RFC 7231, 6.3.5
  623. StatusResetContent = http.StatusResetContent // RFC 7231, 6.3.6
  624. StatusPartialContent = http.StatusPartialContent // RFC 7233, 4.1
  625. StatusMultiStatus = http.StatusMultiStatus // RFC 4918, 11.1
  626. StatusAlreadyReported = http.StatusAlreadyReported // RFC 5842, 7.1
  627. StatusIMUsed = http.StatusIMUsed // RFC 3229, 10.4.1
  628. StatusMultipleChoices = http.StatusMultipleChoices // RFC 7231, 6.4.1
  629. StatusMovedPermanently = http.StatusMovedPermanently // RFC 7231, 6.4.2
  630. StatusFound = http.StatusFound // RFC 7231, 6.4.3
  631. StatusSeeOther = http.StatusSeeOther // RFC 7231, 6.4.4
  632. StatusNotModified = http.StatusNotModified // RFC 7232, 4.1
  633. StatusUseProxy = http.StatusUseProxy // RFC 7231, 6.4.5
  634. _ = 306 // RFC 7231, 6.4.6 (Unused)
  635. StatusTemporaryRedirect = http.StatusTemporaryRedirect // RFC 7231, 6.4.7
  636. StatusPermanentRedirect = http.StatusPermanentRedirect // RFC 7538, 3
  637. StatusBadRequest = http.StatusBadRequest // RFC 7231, 6.5.1
  638. StatusUnauthorized = http.StatusUnauthorized // RFC 7235, 3.1
  639. StatusPaymentRequired = http.StatusPaymentRequired // RFC 7231, 6.5.2
  640. StatusForbidden = http.StatusForbidden // RFC 7231, 6.5.3
  641. StatusNotFound = http.StatusNotFound // RFC 7231, 6.5.4
  642. StatusMethodNotAllowed = http.StatusMethodNotAllowed // RFC 7231, 6.5.5
  643. StatusNotAcceptable = http.StatusNotAcceptable // RFC 7231, 6.5.6
  644. StatusProxyAuthRequired = http.StatusProxyAuthRequired // RFC 7235, 3.2
  645. StatusRequestTimeout = http.StatusRequestTimeout // RFC 7231, 6.5.7
  646. StatusConflict = http.StatusConflict // RFC 7231, 6.5.8
  647. StatusGone = http.StatusGone // RFC 7231, 6.5.9
  648. StatusLengthRequired = http.StatusLengthRequired // RFC 7231, 6.5.10
  649. StatusPreconditionFailed = http.StatusPreconditionFailed // RFC 7232, 4.2
  650. StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge // RFC 7231, 6.5.11
  651. StatusRequestURITooLong = http.StatusRequestURITooLong // RFC 7231, 6.5.12
  652. StatusUnsupportedMediaType = http.StatusUnsupportedMediaType // RFC 7231, 6.5.13
  653. StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable // RFC 7233, 4.4
  654. StatusExpectationFailed = http.StatusExpectationFailed // RFC 7231, 6.5.14
  655. StatusTeapot = http.StatusTeapot // RFC 7168, 2.3.3
  656. StatusMisdirectedRequest = http.StatusMisdirectedRequest // RFC 7540, 9.1.2
  657. StatusUnprocessableEntity = http.StatusUnprocessableEntity // RFC 4918, 11.2
  658. StatusLocked = http.StatusLocked // RFC 4918, 11.3
  659. StatusFailedDependency = http.StatusFailedDependency // RFC 4918, 11.4
  660. StatusTooEarly = http.StatusTooEarly // RFC 8470, 5.2.
  661. StatusUpgradeRequired = http.StatusUpgradeRequired // RFC 7231, 6.5.15
  662. StatusPreconditionRequired = http.StatusPreconditionRequired // RFC 6585, 3
  663. StatusTooManyRequests = http.StatusTooManyRequests // RFC 6585, 4
  664. StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge // RFC 6585, 5
  665. StatusUnavailableForLegalReasons = http.StatusUnavailableForLegalReasons // RFC 7725, 3
  666. // Unofficial Client Errors.
  667. StatusPageExpired = context.StatusPageExpired
  668. StatusBlockedByWindowsParentalControls = context.StatusBlockedByWindowsParentalControls
  669. StatusInvalidToken = context.StatusInvalidToken
  670. StatusTokenRequired = context.StatusTokenRequired
  671. //
  672. StatusInternalServerError = http.StatusInternalServerError // RFC 7231, 6.6.1
  673. StatusNotImplemented = http.StatusNotImplemented // RFC 7231, 6.6.2
  674. StatusBadGateway = http.StatusBadGateway // RFC 7231, 6.6.3
  675. StatusServiceUnavailable = http.StatusServiceUnavailable // RFC 7231, 6.6.4
  676. StatusGatewayTimeout = http.StatusGatewayTimeout // RFC 7231, 6.6.5
  677. StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported // RFC 7231, 6.6.6
  678. StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates // RFC 2295, 8.1
  679. StatusInsufficientStorage = http.StatusInsufficientStorage // RFC 4918, 11.5
  680. StatusLoopDetected = http.StatusLoopDetected // RFC 5842, 7.2
  681. StatusNotExtended = http.StatusNotExtended // RFC 2774, 7
  682. StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired // RFC 6585, 6
  683. // Unofficial Server Errors.
  684. StatusBandwidthLimitExceeded = context.StatusBandwidthLimitExceeded
  685. StatusInvalidSSLCertificate = context.StatusInvalidSSLCertificate
  686. StatusSiteOverloaded = context.StatusSiteOverloaded
  687. StatusSiteFrozen = context.StatusSiteFrozen
  688. StatusNetworkReadTimeout = context.StatusNetworkReadTimeout
  689. )
  690. var (
  691. // StatusText returns a text for the HTTP status code. It returns the empty
  692. // string if the code is unknown.
  693. //
  694. // Shortcut for core/router#StatusText.
  695. StatusText = context.StatusText
  696. // RegisterMethods adds custom http methods to the "AllMethods" list.
  697. // Use it on initialization of your program.
  698. //
  699. // Shortcut for core/router#RegisterMethods.
  700. RegisterMethods = router.RegisterMethods
  701. // WebDAVMethods contains a list of WebDAV HTTP Verbs.
  702. // Register using RegiterMethods package-level function or
  703. // through HandleMany party-level method.
  704. WebDAVMethods = []string{
  705. MethodGet,
  706. MethodHead,
  707. MethodPatch,
  708. MethodPut,
  709. MethodPost,
  710. MethodDelete,
  711. MethodOptions,
  712. MethodConnect,
  713. MethodTrace,
  714. "MKCOL",
  715. "COPY",
  716. "MOVE",
  717. "LOCK",
  718. "UNLOCK",
  719. "PROPFIND",
  720. "PROPPATCH",
  721. "LINK",
  722. "UNLINK",
  723. "PURGE",
  724. "VIEW",
  725. }
  726. )
  727. var globalPatches = &GlobalPatches{
  728. contextPatches: &ContextPatches{
  729. writers: &ContextWriterPatches{},
  730. },
  731. }
  732. // GlobalPatches is a singleton features a uniform way to apply global/package-level modifications.
  733. //
  734. // See the `Patches` package-level function.
  735. type GlobalPatches struct {
  736. contextPatches *ContextPatches
  737. }
  738. // Patches returns the singleton of GlobalPatches, an easy way to modify
  739. // global(package-level) configuration for Iris applications.
  740. //
  741. // See its `Context` method.
  742. //
  743. // Example: https://github.com/kataras/iris/blob/main/_examples/response-writer/json-third-party/main.go
  744. func Patches() *GlobalPatches { // singleton.
  745. return globalPatches
  746. }
  747. // Context returns the available context patches.
  748. func (p *GlobalPatches) Context() *ContextPatches {
  749. return p.contextPatches
  750. }
  751. // ContextPatches contains the available global Iris context modifications.
  752. type ContextPatches struct {
  753. writers *ContextWriterPatches
  754. }
  755. // Writers returns the available global Iris context modifications for REST writers.
  756. func (cp *ContextPatches) Writers() *ContextWriterPatches {
  757. return cp.writers
  758. }
  759. // GetDomain modifies the way a domain is fetched from `Context#Domain` method,
  760. // which is used on subdomain redirect feature, i18n's language cookie for subdomain sharing
  761. // and the rewrite middleware.
  762. func (cp *ContextPatches) GetDomain(patchFunc func(hostport string) string) {
  763. context.GetDomain = patchFunc
  764. }
  765. // SetCookieKVExpiration modifies the default cookie expiration time on `Context#SetCookieKV` method.
  766. func (cp *ContextPatches) SetCookieKVExpiration(patch time.Duration) {
  767. context.SetCookieKVExpiration = patch
  768. }
  769. // ResolveHTTPFS modifies the default way to resolve a filesystem by any type of value.
  770. // It affects the Application's API Builder's `HandleDir` method.
  771. func (cp *ContextPatches) ResolveHTTPFS(patchFunc func(fsOrDir interface{}) http.FileSystem) {
  772. context.ResolveHTTPFS = patchFunc
  773. }
  774. // ResolveHTTPFS modifies the default way to resolve a filesystem by any type of value.
  775. // It affects the view engine's filesystem resolver.
  776. func (cp *ContextPatches) ResolveFS(patchFunc func(fsOrDir interface{}) fs.FS) {
  777. context.ResolveFS = patchFunc
  778. }
  779. // ContextWriterPatches features the context's writers patches.
  780. type ContextWriterPatches struct{}
  781. // JSON sets a custom function which runs and overrides the default behavior of the `Context#JSON` method.
  782. func (cwp *ContextWriterPatches) JSON(patchFunc func(ctx Context, v interface{}, options *JSON) error) {
  783. context.WriteJSON = patchFunc
  784. }
  785. // JSONP sets a custom function which runs and overrides the default behavior of the `Context#JSONP` method.
  786. func (cwp *ContextWriterPatches) JSONP(patchFunc func(ctx Context, v interface{}, options *JSONP) error) {
  787. context.WriteJSONP = patchFunc
  788. }
  789. // XML sets a custom function which runs and overrides the default behavior of the `Context#XML` method.
  790. func (cwp *ContextWriterPatches) XML(patchFunc func(ctx Context, v interface{}, options *XML) error) {
  791. context.WriteXML = patchFunc
  792. }
  793. // Markdown sets a custom function which runs and overrides the default behavior of the `Context#Markdown` method.
  794. func (cwp *ContextWriterPatches) Markdown(patchFunc func(ctx Context, v []byte, options *Markdown) error) {
  795. context.WriteMarkdown = patchFunc
  796. }
  797. // YAML sets a custom function which runs and overrides the default behavior of the `Context#YAML` method.
  798. func (cwp *ContextWriterPatches) YAML(patchFunc func(ctx Context, v interface{}, indentSpace int) error) {
  799. context.WriteYAML = patchFunc
  800. }
  801. // Singleton is a structure which can be used as an embedded field on
  802. // struct/controllers that should be marked as singletons on `PartyConfigure` or `MVC` Applications.
  803. type Singleton struct{}
  804. // Singleton returns true as this controller is a singleton.
  805. func (c Singleton) Singleton() bool { return true }