configuration.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. package iris
  2. import (
  3. "fmt"
  4. "os"
  5. "os/user"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "time"
  10. "github.com/kataras/iris/v12/context"
  11. "github.com/kataras/iris/v12/core/netutil"
  12. "github.com/BurntSushi/toml"
  13. "github.com/kataras/golog"
  14. "github.com/kataras/sitemap"
  15. "github.com/kataras/tunnel"
  16. "gopkg.in/yaml.v3"
  17. )
  18. const globalConfigurationKeyword = "~"
  19. // homeConfigurationFilename returns the physical location of the global configuration(yaml or toml) file.
  20. // This is useful when we run multiple iris servers that share the same
  21. // configuration, even with custom values at its "Other" field.
  22. // It will return a file location
  23. // which targets to $HOME or %HOMEDRIVE%+%HOMEPATH% + "iris" + the given "ext".
  24. func homeConfigurationFilename(ext string) string {
  25. return filepath.Join(homeDir(), "iris"+ext)
  26. }
  27. func homeDir() (home string) {
  28. u, err := user.Current()
  29. if u != nil && err == nil {
  30. home = u.HomeDir
  31. }
  32. if home == "" {
  33. home = os.Getenv("HOME")
  34. }
  35. if home == "" {
  36. if runtime.GOOS == "plan9" {
  37. home = os.Getenv("home")
  38. } else if runtime.GOOS == "windows" {
  39. home = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  40. if home == "" {
  41. home = os.Getenv("USERPROFILE")
  42. }
  43. }
  44. }
  45. return
  46. }
  47. func parseYAML(filename string) (Configuration, error) {
  48. c := DefaultConfiguration()
  49. // get the abs
  50. // which will try to find the 'filename' from current workind dir too.
  51. yamlAbsPath, err := filepath.Abs(filename)
  52. if err != nil {
  53. return c, fmt.Errorf("parse yaml: %w", err)
  54. }
  55. // read the raw contents of the file
  56. data, err := os.ReadFile(yamlAbsPath)
  57. if err != nil {
  58. return c, fmt.Errorf("parse yaml: %w", err)
  59. }
  60. // put the file's contents as yaml to the default configuration(c)
  61. if err := yaml.Unmarshal(data, &c); err != nil {
  62. return c, fmt.Errorf("parse yaml: %w", err)
  63. }
  64. return c, nil
  65. }
  66. // YAML reads Configuration from a configuration.yml file.
  67. //
  68. // Accepts the absolute path of the cfg.yml.
  69. // An error will be shown to the user via panic with the error message.
  70. // Error may occur when the cfg.yml does not exist or is not formatted correctly.
  71. //
  72. // Note: if the char '~' passed as "filename" then it tries to load and return
  73. // the configuration from the $home_directory + iris.yml,
  74. // see `WithGlobalConfiguration` for more information.
  75. //
  76. // Usage:
  77. // app.Configure(iris.WithConfiguration(iris.YAML("myconfig.yml"))) or
  78. // app.Run([iris.Runner], iris.WithConfiguration(iris.YAML("myconfig.yml"))).
  79. func YAML(filename string) Configuration {
  80. // check for globe configuration file and use that, otherwise
  81. // return the default configuration if file doesn't exist.
  82. if filename == globalConfigurationKeyword {
  83. filename = homeConfigurationFilename(".yml")
  84. if _, err := os.Stat(filename); os.IsNotExist(err) {
  85. panic("default configuration file '" + filename + "' does not exist")
  86. }
  87. }
  88. c, err := parseYAML(filename)
  89. if err != nil {
  90. panic(err)
  91. }
  92. return c
  93. }
  94. // TOML reads Configuration from a toml-compatible document file.
  95. // Read more about toml's implementation at:
  96. // https://github.com/toml-lang/toml
  97. //
  98. // Accepts the absolute path of the configuration file.
  99. // An error will be shown to the user via panic with the error message.
  100. // Error may occur when the file does not exist or is not formatted correctly.
  101. //
  102. // Note: if the char '~' passed as "filename" then it tries to load and return
  103. // the configuration from the $home_directory + iris.tml,
  104. // see `WithGlobalConfiguration` for more information.
  105. //
  106. // Usage:
  107. // app.Configure(iris.WithConfiguration(iris.TOML("myconfig.tml"))) or
  108. // app.Run([iris.Runner], iris.WithConfiguration(iris.TOML("myconfig.tml"))).
  109. func TOML(filename string) Configuration {
  110. c := DefaultConfiguration()
  111. // check for globe configuration file and use that, otherwise
  112. // return the default configuration if file doesn't exist.
  113. if filename == globalConfigurationKeyword {
  114. filename = homeConfigurationFilename(".tml")
  115. if _, err := os.Stat(filename); os.IsNotExist(err) {
  116. panic("default configuration file '" + filename + "' does not exist")
  117. }
  118. }
  119. // get the abs
  120. // which will try to find the 'filename' from current workind dir too.
  121. tomlAbsPath, err := filepath.Abs(filename)
  122. if err != nil {
  123. panic(fmt.Errorf("toml: %w", err))
  124. }
  125. // read the raw contents of the file
  126. data, err := os.ReadFile(tomlAbsPath)
  127. if err != nil {
  128. panic(fmt.Errorf("toml :%w", err))
  129. }
  130. // put the file's contents as toml to the default configuration(c)
  131. if _, err := toml.Decode(string(data), &c); err != nil {
  132. panic(fmt.Errorf("toml :%w", err))
  133. }
  134. // Author's notes:
  135. // The toml's 'usual thing' for key naming is: the_config_key instead of TheConfigKey
  136. // but I am always prefer to use the specific programming language's syntax
  137. // and the original configuration name fields for external configuration files
  138. // so we do 'toml: "TheConfigKeySameAsTheConfigField" instead.
  139. return c
  140. }
  141. // Configurator is just an interface which accepts the framework instance.
  142. //
  143. // It can be used to register a custom configuration with `Configure` in order
  144. // to modify the framework instance.
  145. //
  146. // Currently Configurator is being used to describe the configuration's fields values.
  147. type Configurator func(*Application)
  148. // WithGlobalConfiguration will load the global yaml configuration file
  149. // from the home directory and it will set/override the whole app's configuration
  150. // to that file's contents. The global configuration file can be modified by user
  151. // and be used by multiple iris instances.
  152. //
  153. // This is useful when we run multiple iris servers that share the same
  154. // configuration, even with custom values at its "Other" field.
  155. //
  156. // Usage: `app.Configure(iris.WithGlobalConfiguration)` or `app.Run([iris.Runner], iris.WithGlobalConfiguration)`.
  157. var WithGlobalConfiguration = func(app *Application) {
  158. app.Configure(WithConfiguration(YAML(globalConfigurationKeyword)))
  159. }
  160. // WithLogLevel sets the `Configuration.LogLevel` field.
  161. func WithLogLevel(level string) Configurator {
  162. return func(app *Application) {
  163. if app.logger == nil {
  164. app.logger = golog.Default
  165. }
  166. app.logger.SetLevel(level) // can be fired through app.Configure.
  167. app.config.LogLevel = level
  168. }
  169. }
  170. // WithSocketSharding sets the `Configuration.SocketSharding` field to true.
  171. func WithSocketSharding(app *Application) {
  172. // Note(@kataras): It could be a host Configurator but it's an application setting in order
  173. // to configure it through yaml/toml files as well.
  174. app.config.SocketSharding = true
  175. }
  176. // WithKeepAlive sets the `Configuration.KeepAlive` field to the given duration.
  177. func WithKeepAlive(keepAliveDur time.Duration) Configurator {
  178. return func(app *Application) {
  179. app.config.KeepAlive = keepAliveDur
  180. }
  181. }
  182. // WithTimeout sets the `Configuration.Timeout` field to the given duration.
  183. func WithTimeout(timeoutDur time.Duration, htmlBody ...string) Configurator {
  184. return func(app *Application) {
  185. app.config.Timeout = timeoutDur
  186. if len(htmlBody) > 0 {
  187. app.config.TimeoutMessage = htmlBody[0]
  188. }
  189. }
  190. }
  191. // NonBlocking sets the `Configuration.NonBlocking` field to true.
  192. func NonBlocking() Configurator {
  193. return func(app *Application) {
  194. app.config.NonBlocking = true
  195. }
  196. }
  197. // WithoutServerError will cause to ignore the matched "errors"
  198. // from the main application's `Run/Listen` function.
  199. //
  200. // Usage:
  201. // err := app.Listen(":8080", iris.WithoutServerError(iris.ErrServerClosed))
  202. // will return `nil` if the server's error was `http/iris#ErrServerClosed`.
  203. //
  204. // See `Configuration#IgnoreServerErrors []string` too.
  205. //
  206. // Example: https://github.com/kataras/iris/tree/main/_examples/http-server/listen-addr/omit-server-errors
  207. func WithoutServerError(errors ...error) Configurator {
  208. return func(app *Application) {
  209. if len(errors) == 0 {
  210. return
  211. }
  212. errorsAsString := make([]string, len(errors))
  213. for i, e := range errors {
  214. errorsAsString[i] = e.Error()
  215. }
  216. app.config.IgnoreServerErrors = append(app.config.IgnoreServerErrors, errorsAsString...)
  217. }
  218. }
  219. // WithoutStartupLog turns off the information send, once, to the terminal when the main server is open.
  220. var WithoutStartupLog = func(app *Application) {
  221. app.config.DisableStartupLog = true
  222. }
  223. // WithoutBanner is a conversion for the `WithoutStartupLog` option.
  224. //
  225. // Turns off the information send, once, to the terminal when the main server is open.
  226. var WithoutBanner = WithoutStartupLog
  227. // WithoutInterruptHandler disables the automatic graceful server shutdown
  228. // when control/cmd+C pressed.
  229. var WithoutInterruptHandler = func(app *Application) {
  230. app.config.DisableInterruptHandler = true
  231. }
  232. // WithoutPathCorrection disables the PathCorrection setting.
  233. //
  234. // See `Configuration`.
  235. var WithoutPathCorrection = func(app *Application) {
  236. app.config.DisablePathCorrection = true
  237. }
  238. // WithPathIntelligence enables the EnablePathIntelligence setting.
  239. //
  240. // See `Configuration`.
  241. var WithPathIntelligence = func(app *Application) {
  242. app.config.EnablePathIntelligence = true
  243. }
  244. // WithoutPathCorrectionRedirection disables the PathCorrectionRedirection setting.
  245. //
  246. // See `Configuration`.
  247. var WithoutPathCorrectionRedirection = func(app *Application) {
  248. app.config.DisablePathCorrection = false
  249. app.config.DisablePathCorrectionRedirection = true
  250. }
  251. // WithoutBodyConsumptionOnUnmarshal disables BodyConsumptionOnUnmarshal setting.
  252. //
  253. // See `Configuration`.
  254. var WithoutBodyConsumptionOnUnmarshal = func(app *Application) {
  255. app.config.DisableBodyConsumptionOnUnmarshal = true
  256. }
  257. // WithEmptyFormError enables the setting `FireEmptyFormError`.
  258. //
  259. // See `Configuration`.
  260. var WithEmptyFormError = func(app *Application) {
  261. app.config.FireEmptyFormError = true
  262. }
  263. // WithPathEscape sets the EnablePathEscape setting to true.
  264. //
  265. // See `Configuration`.
  266. var WithPathEscape = func(app *Application) {
  267. app.config.EnablePathEscape = true
  268. }
  269. // WithLowercaseRouting enables for lowercase routing by
  270. // setting the `ForceLowercaseRoutes` to true.
  271. //
  272. // See `Configuration`.
  273. var WithLowercaseRouting = func(app *Application) {
  274. app.config.ForceLowercaseRouting = true
  275. }
  276. // WithDynamicHandler enables for dynamic routing by
  277. // setting the `EnableDynamicHandler` to true.
  278. //
  279. // See `Configuration`.
  280. var WithDynamicHandler = func(app *Application) {
  281. app.config.EnableDynamicHandler = true
  282. }
  283. // WithOptimizations can force the application to optimize for the best performance where is possible.
  284. //
  285. // See `Configuration`.
  286. var WithOptimizations = func(app *Application) {
  287. app.config.EnableOptimizations = true
  288. }
  289. // WithProtoJSON enables the proto marshaler on Context.JSON method.
  290. //
  291. // See `Configuration` for more.
  292. var WithProtoJSON = func(app *Application) {
  293. app.config.EnableProtoJSON = true
  294. }
  295. // WithEasyJSON enables the fast easy json marshaler on Context.JSON method.
  296. //
  297. // See `Configuration` for more.
  298. var WithEasyJSON = func(app *Application) {
  299. app.config.EnableEasyJSON = true
  300. }
  301. // WithFireMethodNotAllowed enables the FireMethodNotAllowed setting.
  302. //
  303. // See `Configuration`.
  304. var WithFireMethodNotAllowed = func(app *Application) {
  305. app.config.FireMethodNotAllowed = true
  306. }
  307. // WithoutAutoFireStatusCode sets the DisableAutoFireStatusCode setting to true.
  308. //
  309. // See `Configuration`.
  310. var WithoutAutoFireStatusCode = func(app *Application) {
  311. app.config.DisableAutoFireStatusCode = true
  312. }
  313. // WithResetOnFireErrorCode sets the ResetOnFireErrorCode setting to true.
  314. //
  315. // See `Configuration`.
  316. var WithResetOnFireErrorCode = func(app *Application) {
  317. app.config.ResetOnFireErrorCode = true
  318. }
  319. // WithURLParamSeparator sets the URLParamSeparator setting to "sep".
  320. //
  321. // See `Configuration`.
  322. var WithURLParamSeparator = func(sep string) Configurator {
  323. return func(app *Application) {
  324. app.config.URLParamSeparator = &sep
  325. }
  326. }
  327. // WithTimeFormat sets the TimeFormat setting.
  328. //
  329. // See `Configuration`.
  330. func WithTimeFormat(timeformat string) Configurator {
  331. return func(app *Application) {
  332. app.config.TimeFormat = timeformat
  333. }
  334. }
  335. // WithCharset sets the Charset setting.
  336. //
  337. // See `Configuration`.
  338. func WithCharset(charset string) Configurator {
  339. return func(app *Application) {
  340. app.config.Charset = charset
  341. }
  342. }
  343. // WithPostMaxMemory sets the maximum post data size
  344. // that a client can send to the server, this differs
  345. // from the overall request body size which can be modified
  346. // by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
  347. //
  348. // Defaults to 32MB or 32 << 20 or 32*iris.MB if you prefer.
  349. func WithPostMaxMemory(limit int64) Configurator {
  350. return func(app *Application) {
  351. app.config.PostMaxMemory = limit
  352. }
  353. }
  354. // WithRemoteAddrHeader adds a new request header name
  355. // that can be used to validate the client's real IP.
  356. func WithRemoteAddrHeader(header ...string) Configurator {
  357. return func(app *Application) {
  358. for _, h := range header {
  359. exists := false
  360. for _, v := range app.config.RemoteAddrHeaders {
  361. if v == h {
  362. exists = true
  363. }
  364. }
  365. if !exists {
  366. app.config.RemoteAddrHeaders = append(app.config.RemoteAddrHeaders, h)
  367. }
  368. }
  369. }
  370. }
  371. // WithoutRemoteAddrHeader removes an existing request header name
  372. // that can be used to validate and parse the client's real IP.
  373. //
  374. // Look `context.RemoteAddr()` for more.
  375. func WithoutRemoteAddrHeader(headerName string) Configurator {
  376. return func(app *Application) {
  377. tmp := app.config.RemoteAddrHeaders[:0]
  378. for _, v := range app.config.RemoteAddrHeaders {
  379. if v != headerName {
  380. tmp = append(tmp, v)
  381. }
  382. }
  383. app.config.RemoteAddrHeaders = tmp
  384. }
  385. }
  386. // WithRemoteAddrPrivateSubnet adds a new private sub-net to be excluded from `context.RemoteAddr`.
  387. // See `WithRemoteAddrHeader` too.
  388. func WithRemoteAddrPrivateSubnet(startIP, endIP string) Configurator {
  389. return func(app *Application) {
  390. app.config.RemoteAddrPrivateSubnets = append(app.config.RemoteAddrPrivateSubnets, netutil.IPRange{
  391. Start: startIP,
  392. End: endIP,
  393. })
  394. }
  395. }
  396. // WithSSLProxyHeader sets a SSLProxyHeaders key value pair.
  397. // Example: WithSSLProxyHeader("X-Forwarded-Proto", "https").
  398. // See `Context.IsSSL` for more.
  399. func WithSSLProxyHeader(headerKey, headerValue string) Configurator {
  400. return func(app *Application) {
  401. if app.config.SSLProxyHeaders == nil {
  402. app.config.SSLProxyHeaders = make(map[string]string)
  403. }
  404. app.config.SSLProxyHeaders[headerKey] = headerValue
  405. }
  406. }
  407. // WithHostProxyHeader sets a HostProxyHeaders key value pair.
  408. // Example: WithHostProxyHeader("X-Host").
  409. // See `Context.Host` for more.
  410. func WithHostProxyHeader(headers ...string) Configurator {
  411. return func(app *Application) {
  412. if app.config.HostProxyHeaders == nil {
  413. app.config.HostProxyHeaders = make(map[string]bool)
  414. }
  415. for _, k := range headers {
  416. app.config.HostProxyHeaders[k] = true
  417. }
  418. }
  419. }
  420. // WithOtherValue adds a value based on a key to the Other setting.
  421. //
  422. // See `Configuration.Other`.
  423. func WithOtherValue(key string, val interface{}) Configurator {
  424. return func(app *Application) {
  425. if app.config.Other == nil {
  426. app.config.Other = make(map[string]interface{})
  427. }
  428. app.config.Other[key] = val
  429. }
  430. }
  431. // WithSitemap enables the sitemap generator.
  432. // Use the Route's `SetLastMod`, `SetChangeFreq` and `SetPriority` to modify
  433. // the sitemap's URL child element properties.
  434. // Excluded routes:
  435. // - dynamic
  436. // - subdomain
  437. // - offline
  438. // - ExcludeSitemap method called
  439. //
  440. // It accepts a "startURL" input argument which
  441. // is the prefix for the registered routes that will be included in the sitemap.
  442. //
  443. // If more than 50,000 static routes are registered then sitemaps will be splitted and a sitemap index will be served in
  444. // /sitemap.xml.
  445. //
  446. // If `Application.I18n.Load/LoadAssets` is called then the sitemap will contain translated links for each static route.
  447. //
  448. // If the result does not complete your needs you can take control
  449. // and use the github.com/kataras/sitemap package to generate a customized one instead.
  450. //
  451. // Example: https://github.com/kataras/iris/tree/main/_examples/sitemap.
  452. func WithSitemap(startURL string) Configurator {
  453. sitemaps := sitemap.New(startURL)
  454. return func(app *Application) {
  455. var defaultLang string
  456. if tags := app.I18n.Tags(); len(tags) > 0 {
  457. defaultLang = tags[0].String()
  458. sitemaps.DefaultLang(defaultLang)
  459. }
  460. for _, r := range app.GetRoutes() {
  461. if !r.IsStatic() || r.Subdomain != "" || !r.IsOnline() || r.NoSitemap {
  462. continue
  463. }
  464. loc := r.StaticPath()
  465. var translatedLinks []sitemap.Link
  466. for _, tag := range app.I18n.Tags() {
  467. lang := tag.String()
  468. langPath := lang
  469. href := ""
  470. if lang == defaultLang {
  471. // http://domain.com/en-US/path to just http://domain.com/path if en-US is the default language.
  472. langPath = ""
  473. }
  474. if app.I18n.PathRedirect {
  475. // then use the path prefix.
  476. // e.g. http://domain.com/el-GR/path
  477. if langPath == "" { // fix double slashes http://domain.com// when self-included default language.
  478. href = loc
  479. } else {
  480. href = "/" + langPath + loc
  481. }
  482. } else if app.I18n.Subdomain {
  483. // then use the subdomain.
  484. // e.g. http://el.domain.com/path
  485. scheme := netutil.ResolveSchemeFromVHost(startURL)
  486. host := strings.TrimLeft(startURL, scheme)
  487. if langPath != "" {
  488. href = scheme + strings.Split(langPath, "-")[0] + "." + host + loc
  489. } else {
  490. href = loc
  491. }
  492. } else if p := app.I18n.URLParameter; p != "" {
  493. // then use the URL parameter.
  494. // e.g. http://domain.com/path?lang=el-GR
  495. href = loc + "?" + p + "=" + lang
  496. } else {
  497. // then skip it, we can't generate the link at this state.
  498. continue
  499. }
  500. translatedLinks = append(translatedLinks, sitemap.Link{
  501. Rel: "alternate",
  502. Hreflang: lang,
  503. Href: href,
  504. })
  505. }
  506. sitemaps.URL(sitemap.URL{
  507. Loc: loc,
  508. LastMod: r.LastMod,
  509. ChangeFreq: r.ChangeFreq,
  510. Priority: r.Priority,
  511. Links: translatedLinks,
  512. })
  513. }
  514. for _, s := range sitemaps.Build() {
  515. contentCopy := make([]byte, len(s.Content))
  516. copy(contentCopy, s.Content)
  517. handler := func(ctx Context) {
  518. ctx.ContentType(context.ContentXMLHeaderValue)
  519. ctx.Write(contentCopy) // nolint:errcheck
  520. }
  521. if app.builded {
  522. routes := app.CreateRoutes([]string{MethodGet, MethodHead, MethodOptions}, s.Path, handler)
  523. for _, r := range routes {
  524. if err := app.Router.AddRouteUnsafe(r); err != nil {
  525. app.Logger().Errorf("sitemap route: %v", err)
  526. }
  527. }
  528. } else {
  529. app.HandleMany("GET HEAD OPTIONS", s.Path, handler)
  530. }
  531. }
  532. }
  533. }
  534. // WithTunneling is the `iris.Configurator` for the `iris.Configuration.Tunneling` field.
  535. // It's used to enable http tunneling for an Iris Application, per registered host
  536. //
  537. // Alternatively use the `iris.WithConfiguration(iris.Configuration{Tunneling: iris.TunnelingConfiguration{ ...}}}`.
  538. var WithTunneling = func(app *Application) {
  539. conf := TunnelingConfiguration{
  540. Tunnels: []Tunnel{{}}, // create empty tunnel, its addr and name are set right before host serve.
  541. }
  542. app.config.Tunneling = conf
  543. }
  544. type (
  545. // TunnelingConfiguration contains configuration
  546. // for the optional tunneling through ngrok feature.
  547. // Note that the ngrok should be already installed at the host machine.
  548. TunnelingConfiguration = tunnel.Configuration
  549. // Tunnel is the Tunnels field of the TunnelingConfiguration structure.
  550. Tunnel = tunnel.Tunnel
  551. )
  552. // Configuration holds the necessary settings for an Iris Application instance.
  553. // All fields are optionally, the default values will work for a common web application.
  554. //
  555. // A Configuration value can be passed through `WithConfiguration` Configurator.
  556. // Usage:
  557. // conf := iris.Configuration{ ... }
  558. // app := iris.New()
  559. // app.Configure(iris.WithConfiguration(conf)) OR
  560. // app.Run/Listen(..., iris.WithConfiguration(conf)).
  561. type Configuration struct {
  562. // VHost lets you customize the trusted domain this server should run on.
  563. // Its value will be used as the return value of Context.Domain() too.
  564. // It can be retrieved by the context if needed (i.e router for subdomains)
  565. VHost string `ini:"v_host" json:"vHost" yaml:"VHost" toml:"VHost" env:"V_HOST"`
  566. // LogLevel is the log level the application should use to output messages.
  567. // Logger, by default, is mostly used on Build state but it is also possible
  568. // that debug error messages could be thrown when the app is running, e.g.
  569. // when malformed data structures try to be sent on Client (i.e Context.JSON/JSONP/XML...).
  570. //
  571. // Defaults to "info". Possible values are:
  572. // * "disable"
  573. // * "fatal"
  574. // * "error"
  575. // * "warn"
  576. // * "info"
  577. // * "debug"
  578. LogLevel string `ini:"log_level" json:"logLevel" yaml:"LogLevel" toml:"LogLevel" env:"LOG_LEVEL"`
  579. // SocketSharding enables SO_REUSEPORT (or SO_REUSEADDR for windows)
  580. // on all registered Hosts.
  581. // This option allows linear scaling server performance on multi-CPU servers.
  582. //
  583. // Please read the following:
  584. // 1. https://stackoverflow.com/a/14388707
  585. // 2. https://stackoverflow.com/a/59692868
  586. // 3. https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
  587. // 4. (BOOK) Learning HTTP/2: A Practical Guide for Beginners:
  588. // Page 37, To Shard or Not to Shard?
  589. //
  590. // Defaults to false.
  591. SocketSharding bool `ini:"socket_sharding" json:"socketSharding" yaml:"SocketSharding" toml:"SocketSharding" env:"SOCKET_SHARDING"`
  592. // KeepAlive sets the TCP connection's keep-alive duration.
  593. // If set to greater than zero then a tcp listener featured keep alive
  594. // will be used instead of the simple tcp one.
  595. //
  596. // Defaults to 0.
  597. KeepAlive time.Duration `ini:"keepalive" json:"keepAlive" yaml:"KeepAlive" toml:"KeepAlive" env:"KEEP_ALIVE"`
  598. // Timeout wraps the application's router with an http timeout handler
  599. // if the value is greater than zero.
  600. //
  601. // The underline response writer supports the Pusher interface but does not support
  602. // the Hijacker or Flusher interfaces when Timeout handler is registered.
  603. //
  604. // Read more at: https://pkg.go.dev/net/http#TimeoutHandler.
  605. Timeout time.Duration `ini:"timeout" json:"timeout" yaml:"Timeout" toml:"Timeout"`
  606. // TimeoutMessage specifies the HTML body when a handler hits its life time based
  607. // on the Timeout configuration field.
  608. TimeoutMessage string `ini:"timeout_message" json:"timeoutMessage" yaml:"TimeoutMessage" toml:"TimeoutMessage"`
  609. // NonBlocking, if set to true then the server will start listening for incoming connections
  610. // without blocking the main goroutine. Use the Application.Wait method to block and wait for the server to be up and running.
  611. NonBlocking bool `ini:"non_blocking" json:"nonBlocking" yaml:"NonBlocking" toml:"NonBlocking"`
  612. // Tunneling can be optionally set to enable ngrok http(s) tunneling for this Iris app instance.
  613. // See the `WithTunneling` Configurator too.
  614. Tunneling TunnelingConfiguration `ini:"tunneling" json:"tunneling,omitempty" yaml:"Tunneling" toml:"Tunneling"`
  615. // IgnoreServerErrors will cause to ignore the matched "errors"
  616. // from the main application's `Run` function.
  617. // This is a slice of string, not a slice of error
  618. // users can register these errors using yaml or toml configuration file
  619. // like the rest of the configuration fields.
  620. //
  621. // See `WithoutServerError(...)` function too.
  622. //
  623. // Example: https://github.com/kataras/iris/tree/main/_examples/http-server/listen-addr/omit-server-errors
  624. //
  625. // Defaults to an empty slice.
  626. IgnoreServerErrors []string `ini:"ignore_server_errors" json:"ignoreServerErrors,omitempty" yaml:"IgnoreServerErrors" toml:"IgnoreServerErrors"`
  627. // DisableStartupLog if set to true then it turns off the write banner on server startup.
  628. //
  629. // Defaults to false.
  630. DisableStartupLog bool `ini:"disable_startup_log" json:"disableStartupLog,omitempty" yaml:"DisableStartupLog" toml:"DisableStartupLog"`
  631. // DisableInterruptHandler if set to true then it disables the automatic graceful server shutdown
  632. // when control/cmd+C pressed.
  633. // Turn this to true if you're planning to handle this by your own via a custom host.Task.
  634. //
  635. // Defaults to false.
  636. DisableInterruptHandler bool `ini:"disable_interrupt_handler" json:"disableInterruptHandler,omitempty" yaml:"DisableInterruptHandler" toml:"DisableInterruptHandler"`
  637. // DisablePathCorrection disables the correcting
  638. // and redirecting or executing directly the handler of
  639. // the requested path to the registered path
  640. // for example, if /home/ path is requested but no handler for this Route found,
  641. // then the Router checks if /home handler exists, if yes,
  642. // (permanent)redirects the client to the correct path /home.
  643. //
  644. // See `DisablePathCorrectionRedirection` to enable direct handler execution instead of redirection.
  645. //
  646. // Defaults to false.
  647. DisablePathCorrection bool `ini:"disable_path_correction" json:"disablePathCorrection,omitempty" yaml:"DisablePathCorrection" toml:"DisablePathCorrection"`
  648. // DisablePathCorrectionRedirection works whenever configuration.DisablePathCorrection is set to false
  649. // and if DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without
  650. // the trailing slash ("/") instead of send a redirection status.
  651. //
  652. // Defaults to false.
  653. DisablePathCorrectionRedirection bool `ini:"disable_path_correction_redirection" json:"disablePathCorrectionRedirection,omitempty" yaml:"DisablePathCorrectionRedirection" toml:"DisablePathCorrectionRedirection"`
  654. // EnablePathIntelligence if set to true,
  655. // the router will redirect HTTP "GET" not found pages to the most closest one path(if any). For example
  656. // you register a route at "/contact" path -
  657. // a client tries to reach it by "/cont", the path will be automatic fixed
  658. // and the client will be redirected to the "/contact" path
  659. // instead of getting a 404 not found response back.
  660. //
  661. // Defaults to false.
  662. EnablePathIntelligence bool `ini:"enable_path_intelligence" json:"enablePathIntelligence,omitempty" yaml:"EnablePathIntelligence" toml:"EnablePathIntelligence"`
  663. // EnablePathEscape when is true then its escapes the path and the named parameters (if any).
  664. // When do you need to Disable(false) it:
  665. // accepts parameters with slash '/'
  666. // Request: http://localhost:8080/details/Project%2FDelta
  667. // ctx.Param("project") returns the raw named parameter: Project%2FDelta
  668. // which you can escape it manually with net/url:
  669. // projectName, _ := url.QueryUnescape(c.Param("project").
  670. //
  671. // Defaults to false.
  672. EnablePathEscape bool `ini:"enable_path_escape" json:"enablePathEscape,omitempty" yaml:"EnablePathEscape" toml:"EnablePathEscape"`
  673. // ForceLowercaseRouting if enabled, converts all registered routes paths to lowercase
  674. // and it does lowercase the request path too for matching.
  675. //
  676. // Defaults to false.
  677. ForceLowercaseRouting bool `ini:"force_lowercase_routing" json:"forceLowercaseRouting,omitempty" yaml:"ForceLowercaseRouting" toml:"ForceLowercaseRouting"`
  678. // EnableOptimizations enables dynamic request handler.
  679. // It gives the router the feature to add routes while in serve-time,
  680. // when `RefreshRouter` is called.
  681. // If this setting is set to true, the request handler will use a mutex for data(trie routing) protection,
  682. // hence the performance cost.
  683. //
  684. // Defaults to false.
  685. EnableDynamicHandler bool `ini:"enable_dynamic_handler" json:"enableDynamicHandler,omitempty" yaml:"EnableDynamicHandler" toml:"EnableDynamicHandler"`
  686. // FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and
  687. // fires the 405 error instead of 404
  688. // Defaults to false.
  689. FireMethodNotAllowed bool `ini:"fire_method_not_allowed" json:"fireMethodNotAllowed,omitempty" yaml:"FireMethodNotAllowed" toml:"FireMethodNotAllowed"`
  690. // DisableAutoFireStatusCode if true then it turns off the http error status code
  691. // handler automatic execution on error code from a `Context.StatusCode` call.
  692. // By-default a custom http error handler will be fired when "Context.StatusCode(errorCode)" called.
  693. //
  694. // Defaults to false.
  695. DisableAutoFireStatusCode bool `ini:"disable_auto_fire_status_code" json:"disableAutoFireStatusCode,omitempty" yaml:"DisableAutoFireStatusCode" toml:"DisableAutoFireStatusCode"`
  696. // ResetOnFireErrorCode if true then any previously response body or headers through
  697. // response recorder will be ignored and the router
  698. // will fire the registered (or default) HTTP error handler instead.
  699. // See `core/router/handler#FireErrorCode` and `Context.EndRequest` for more details.
  700. //
  701. // Read more at: https://github.com/kataras/iris/issues/1531
  702. //
  703. // Defaults to false.
  704. ResetOnFireErrorCode bool `ini:"reset_on_fire_error_code" json:"resetOnFireErrorCode,omitempty" yaml:"ResetOnFireErrorCode" toml:"ResetOnFireErrorCode"`
  705. // URLParamSeparator defines the character(s) separator for Context.URLParamSlice.
  706. // If empty or null then request url parameters with comma separated values will be retrieved as one.
  707. //
  708. // Defaults to comma ",".
  709. URLParamSeparator *string `ini:"url_param_separator" json:"urlParamSeparator,omitempty" yaml:"URLParamSeparator" toml:"URLParamSeparator"`
  710. // EnableOptimization when this field is true
  711. // then the application tries to optimize for the best performance where is possible.
  712. //
  713. // Defaults to false.
  714. // Deprecated. As of version 12.2.x this field does nothing.
  715. EnableOptimizations bool `ini:"enable_optimizations" json:"enableOptimizations,omitempty" yaml:"EnableOptimizations" toml:"EnableOptimizations"`
  716. // EnableProtoJSON when this field is true
  717. // enables the proto marshaler on given proto messages when calling the Context.JSON method.
  718. //
  719. // Defaults to false.
  720. EnableProtoJSON bool `ini:"enable_proto_json" json:"enableProtoJSON,omitempty" yaml:"EnableProtoJSON" toml:"EnableProtoJSON"`
  721. // EnableEasyJSON when this field is true
  722. // enables the fast easy json marshaler on compatible struct values when calling the Context.JSON method.
  723. //
  724. // Defaults to false.
  725. EnableEasyJSON bool `ini:"enable_easy_json" json:"enableEasyJSON,omitempty" yaml:"EnableEasyJSON" toml:"EnableEasyJSON"`
  726. // DisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
  727. // If set to true then it
  728. // disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`.
  729. //
  730. // By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`,
  731. // if this field set to true then a new buffer will be created to read from and the request body.
  732. // The body will not be changed and existing data before the
  733. // context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.
  734. //
  735. // See `Context.RecordRequestBody` method for the same feature, per-request.
  736. DisableBodyConsumptionOnUnmarshal bool `ini:"disable_body_consumption" json:"disableBodyConsumptionOnUnmarshal,omitempty" yaml:"DisableBodyConsumptionOnUnmarshal" toml:"DisableBodyConsumptionOnUnmarshal"`
  737. // FireEmptyFormError returns if set to tue true then the `context.ReadForm/ReadQuery/ReadBody`
  738. // will return an `iris.ErrEmptyForm` on empty request form data.
  739. FireEmptyFormError bool `ini:"fire_empty_form_error" json:"fireEmptyFormError,omitempty" yaml:"FireEmptyFormError" toml:"FireEmptyFormError"`
  740. // TimeFormat time format for any kind of datetime parsing
  741. // Defaults to "Mon, 02 Jan 2006 15:04:05 GMT".
  742. TimeFormat string `ini:"time_format" json:"timeFormat,omitempty" yaml:"TimeFormat" toml:"TimeFormat"`
  743. // Charset character encoding for various rendering
  744. // used for templates and the rest of the responses
  745. // Defaults to "utf-8".
  746. Charset string `ini:"charset" json:"charset,omitempty" yaml:"Charset" toml:"Charset"`
  747. // PostMaxMemory sets the maximum post data size
  748. // that a client can send to the server, this differs
  749. // from the overall request body size which can be modified
  750. // by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
  751. //
  752. // Defaults to 32MB or 32 << 20 if you prefer.
  753. PostMaxMemory int64 `ini:"post_max_memory" json:"postMaxMemory" yaml:"PostMaxMemory" toml:"PostMaxMemory"`
  754. // +----------------------------------------------------+
  755. // | Context's keys for values used on various featuers |
  756. // +----------------------------------------------------+
  757. // Context values' keys for various features.
  758. //
  759. // LocaleContextKey is used by i18n to get the current request's locale, which contains a translate function too.
  760. //
  761. // Defaults to "iris.locale".
  762. LocaleContextKey string `ini:"locale_context_key" json:"localeContextKey,omitempty" yaml:"LocaleContextKey" toml:"LocaleContextKey"`
  763. // LanguageContextKey is the context key which a language can be modified by a middleware.
  764. // It has the highest priority over the rest and if it is empty then it is ignored,
  765. // if it set to a static string of "default" or to the default language's code
  766. // then the rest of the language extractors will not be called at all and
  767. // the default language will be set instead.
  768. //
  769. // Use with `Context.SetLanguage("el-GR")`.
  770. //
  771. // See `i18n.ExtractFunc` for a more organised way of the same feature.
  772. // Defaults to "iris.locale.language".
  773. LanguageContextKey string `ini:"language_context_key" json:"languageContextKey,omitempty" yaml:"LanguageContextKey" toml:"LanguageContextKey"`
  774. // LanguageInputContextKey is the context key of a language that is given by the end-user.
  775. // It's the real user input of the language string, matched or not.
  776. //
  777. // Defaults to "iris.locale.language.input".
  778. LanguageInputContextKey string `ini:"language_input_context_key" json:"languageInputContextKey,omitempty" yaml:"LanguageInputContextKey" toml:"LanguageInputContextKey"`
  779. // VersionContextKey is the context key which an API Version can be modified
  780. // via a middleware through `SetVersion` method, e.g. `versioning.SetVersion(ctx, ">=1.0.0 <2.0.0")`.
  781. // Defaults to "iris.api.version".
  782. VersionContextKey string `ini:"version_context_key" json:"versionContextKey" yaml:"VersionContextKey" toml:"VersionContextKey"`
  783. // VersionAliasesContextKey is the context key which the versioning feature
  784. // can look up for alternative values of a version and fallback to that.
  785. // Head over to the versioning package for more.
  786. // Defaults to "iris.api.version.aliases"
  787. VersionAliasesContextKey string `ini:"version_aliases_context_key" json:"versionAliasesContextKey" yaml:"VersionAliasesContextKey" toml:"VersionAliasesContextKey"`
  788. // ViewEngineContextKey is the context's values key
  789. // responsible to store and retrieve(view.Engine) the current view engine.
  790. // A middleware or a Party can modify its associated value to change
  791. // a view engine that `ctx.View` will render through.
  792. // If not an engine is registered by the end-developer
  793. // then its associated value is always nil,
  794. // meaning that the default value is nil.
  795. // See `Party.RegisterView` and `Context.ViewEngine` methods as well.
  796. //
  797. // Defaults to "iris.view.engine".
  798. ViewEngineContextKey string `ini:"view_engine_context_key" json:"viewEngineContextKey,omitempty" yaml:"ViewEngineContextKey" toml:"ViewEngineContextKey"`
  799. // ViewLayoutContextKey is the context's values key
  800. // responsible to store and retrieve(string) the current view layout.
  801. // A middleware can modify its associated value to change
  802. // the layout that `ctx.View` will use to render a template.
  803. //
  804. // Defaults to "iris.view.layout".
  805. ViewLayoutContextKey string `ini:"view_layout_context_key" json:"viewLayoutContextKey,omitempty" yaml:"ViewLayoutContextKey" toml:"ViewLayoutContextKey"`
  806. // ViewDataContextKey is the context's values key
  807. // responsible to store and retrieve(interface{}) the current view binding data.
  808. // A middleware can modify its associated value to change
  809. // the template's data on-fly.
  810. //
  811. // Defaults to "iris.view.data".
  812. ViewDataContextKey string `ini:"view_data_context_key" json:"viewDataContextKey,omitempty" yaml:"ViewDataContextKey" toml:"ViewDataContextKey"`
  813. // FallbackViewContextKey is the context's values key
  814. // responsible to store the view fallback information.
  815. //
  816. // Defaults to "iris.view.fallback".
  817. FallbackViewContextKey string `ini:"fallback_view_context_key" json:"fallbackViewContextKey,omitempty" yaml:"FallbackViewContextKey" toml:"FallbackViewContextKey"`
  818. // RemoteAddrHeaders are the allowed request headers names
  819. // that can be valid to parse the client's IP based on.
  820. // By-default no "X-" header is consired safe to be used for retrieving the
  821. // client's IP address, because those headers can manually change by
  822. // the client. But sometimes are useful e.g. when behind a proxy
  823. // you want to enable the "X-Forwarded-For" or when cloudflare
  824. // you want to enable the "CF-Connecting-IP", indeed you
  825. // can allow the `ctx.RemoteAddr()` to use any header
  826. // that the client may sent.
  827. //
  828. // Defaults to an empty slice but an example usage is:
  829. // RemoteAddrHeaders {
  830. // "X-Real-Ip",
  831. // "X-Forwarded-For",
  832. // "CF-Connecting-IP",
  833. // "True-Client-Ip",
  834. // "X-Appengine-Remote-Addr",
  835. // }
  836. //
  837. // Look `context.RemoteAddr()` for more.
  838. RemoteAddrHeaders []string `ini:"remote_addr_headers" json:"remoteAddrHeaders,omitempty" yaml:"RemoteAddrHeaders" toml:"RemoteAddrHeaders"`
  839. // RemoteAddrHeadersForce forces the `Context.RemoteAddr()` method
  840. // to return the first entry of a request header as a fallback,
  841. // even if that IP is a part of the `RemoteAddrPrivateSubnets` list.
  842. // The default behavior, if a remote address is part of the `RemoteAddrPrivateSubnets`,
  843. // is to retrieve the IP from the `Request.RemoteAddr` field instead.
  844. RemoteAddrHeadersForce bool `ini:"remote_addr_headers_force" json:"remoteAddrHeadersForce,omitempty" yaml:"RemoteAddrHeadersForce" toml:"RemoteAddrHeadersForce"`
  845. // RemoteAddrPrivateSubnets defines the private sub-networks.
  846. // They are used to be compared against
  847. // IP Addresses fetched through `RemoteAddrHeaders` or `Context.Request.RemoteAddr`.
  848. // For details please navigate through: https://github.com/kataras/iris/issues/1453
  849. // Defaults to:
  850. // {
  851. // Start: "10.0.0.0",
  852. // End: "10.255.255.255",
  853. // },
  854. // {
  855. // Start: "100.64.0.0",
  856. // End: "100.127.255.255",
  857. // },
  858. // {
  859. // Start: "172.16.0.0",
  860. // End: "172.31.255.255",
  861. // },
  862. // {
  863. // Start: "192.0.0.0",
  864. // End: "192.0.0.255",
  865. // },
  866. // {
  867. // Start: "192.168.0.0",
  868. // End: "192.168.255.255",
  869. // },
  870. // {
  871. // Start: "198.18.0.0",
  872. // End: "198.19.255.255",
  873. // }
  874. //
  875. // Look `Context.RemoteAddr()` for more.
  876. RemoteAddrPrivateSubnets []netutil.IPRange `ini:"remote_addr_private_subnets" json:"remoteAddrPrivateSubnets" yaml:"RemoteAddrPrivateSubnets" toml:"RemoteAddrPrivateSubnets"`
  877. // SSLProxyHeaders defines the set of header key values
  878. // that would indicate a valid https Request (look `Context.IsSSL()`).
  879. // Example: `map[string]string{"X-Forwarded-Proto": "https"}`.
  880. //
  881. // Defaults to empty map.
  882. SSLProxyHeaders map[string]string `ini:"ssl_proxy_headers" json:"sslProxyHeaders" yaml:"SSLProxyHeaders" toml:"SSLProxyHeaders"`
  883. // HostProxyHeaders defines the set of headers that may hold a proxied hostname value for the clients.
  884. // Look `Context.Host()` for more.
  885. // Defaults to empty map.
  886. HostProxyHeaders map[string]bool `ini:"host_proxy_headers" json:"hostProxyHeaders" yaml:"HostProxyHeaders" toml:"HostProxyHeaders"`
  887. // Other are the custom, dynamic options, can be empty.
  888. // This field used only by you to set any app's options you want.
  889. //
  890. // Defaults to empty map.
  891. Other map[string]interface{} `ini:"other" json:"other,omitempty" yaml:"Other" toml:"Other"`
  892. }
  893. var _ context.ConfigurationReadOnly = (*Configuration)(nil)
  894. // GetVHost returns the VHost config field.
  895. func (c *Configuration) GetVHost() string {
  896. vhost := c.VHost
  897. return vhost
  898. }
  899. // SetVHost sets the VHost config field.
  900. func (c *Configuration) SetVHost(s string) {
  901. c.VHost = s
  902. }
  903. // GetLogLevel returns the LogLevel field.
  904. func (c *Configuration) GetLogLevel() string {
  905. return c.LogLevel
  906. }
  907. // GetSocketSharding returns the SocketSharding field.
  908. func (c *Configuration) GetSocketSharding() bool {
  909. return c.SocketSharding
  910. }
  911. // GetKeepAlive returns the KeepAlive field.
  912. func (c *Configuration) GetKeepAlive() time.Duration {
  913. return c.KeepAlive
  914. }
  915. // GetTimeout returns the Timeout field.
  916. func (c *Configuration) GetTimeout() time.Duration {
  917. return c.Timeout
  918. }
  919. // GetNonBlocking returns the NonBlocking field.
  920. func (c *Configuration) GetNonBlocking() bool {
  921. return c.NonBlocking
  922. }
  923. // GetTimeoutMessage returns the TimeoutMessage field.
  924. func (c *Configuration) GetTimeoutMessage() string {
  925. return c.TimeoutMessage
  926. }
  927. // GetDisablePathCorrection returns the DisablePathCorrection field.
  928. func (c *Configuration) GetDisablePathCorrection() bool {
  929. return c.DisablePathCorrection
  930. }
  931. // GetDisablePathCorrectionRedirection returns the DisablePathCorrectionRedirection field.
  932. func (c *Configuration) GetDisablePathCorrectionRedirection() bool {
  933. return c.DisablePathCorrectionRedirection
  934. }
  935. // GetEnablePathIntelligence returns the EnablePathIntelligence field.
  936. func (c *Configuration) GetEnablePathIntelligence() bool {
  937. return c.EnablePathIntelligence
  938. }
  939. // GetEnablePathEscape returns the EnablePathEscape field.
  940. func (c *Configuration) GetEnablePathEscape() bool {
  941. return c.EnablePathEscape
  942. }
  943. // GetForceLowercaseRouting returns the ForceLowercaseRouting field.
  944. func (c *Configuration) GetForceLowercaseRouting() bool {
  945. return c.ForceLowercaseRouting
  946. }
  947. // GetEnableDynamicHandler returns the EnableDynamicHandler field.
  948. func (c *Configuration) GetEnableDynamicHandler() bool {
  949. return c.EnableDynamicHandler
  950. }
  951. // GetFireMethodNotAllowed returns the FireMethodNotAllowed field.
  952. func (c *Configuration) GetFireMethodNotAllowed() bool {
  953. return c.FireMethodNotAllowed
  954. }
  955. // GetEnableOptimizations returns the EnableOptimizations.
  956. func (c *Configuration) GetEnableOptimizations() bool {
  957. return c.EnableOptimizations
  958. }
  959. // GetEnableProtoJSON returns the EnableProtoJSON field.
  960. func (c *Configuration) GetEnableProtoJSON() bool {
  961. return c.EnableProtoJSON
  962. }
  963. // GetEnableEasyJSON returns the EnableEasyJSON field.
  964. func (c *Configuration) GetEnableEasyJSON() bool {
  965. return c.EnableEasyJSON
  966. }
  967. // GetDisableBodyConsumptionOnUnmarshal returns the DisableBodyConsumptionOnUnmarshal field.
  968. func (c *Configuration) GetDisableBodyConsumptionOnUnmarshal() bool {
  969. return c.DisableBodyConsumptionOnUnmarshal
  970. }
  971. // GetFireEmptyFormError returns the DisableBodyConsumptionOnUnmarshal field.
  972. func (c *Configuration) GetFireEmptyFormError() bool {
  973. return c.FireEmptyFormError
  974. }
  975. // GetDisableAutoFireStatusCode returns the DisableAutoFireStatusCode field.
  976. func (c *Configuration) GetDisableAutoFireStatusCode() bool {
  977. return c.DisableAutoFireStatusCode
  978. }
  979. // GetResetOnFireErrorCode returns ResetOnFireErrorCode field.
  980. func (c *Configuration) GetResetOnFireErrorCode() bool {
  981. return c.ResetOnFireErrorCode
  982. }
  983. // GetURLParamSeparator returns URLParamSeparator field.
  984. func (c *Configuration) GetURLParamSeparator() *string {
  985. return c.URLParamSeparator
  986. }
  987. // GetTimeFormat returns the TimeFormat field.
  988. func (c *Configuration) GetTimeFormat() string {
  989. return c.TimeFormat
  990. }
  991. // GetCharset returns the Charset field.
  992. func (c *Configuration) GetCharset() string {
  993. return c.Charset
  994. }
  995. // GetPostMaxMemory returns the PostMaxMemory field.
  996. func (c *Configuration) GetPostMaxMemory() int64 {
  997. return c.PostMaxMemory
  998. }
  999. // GetLocaleContextKey returns the LocaleContextKey field.
  1000. func (c *Configuration) GetLocaleContextKey() string {
  1001. return c.LocaleContextKey
  1002. }
  1003. // GetLanguageContextKey returns the LanguageContextKey field.
  1004. func (c *Configuration) GetLanguageContextKey() string {
  1005. return c.LanguageContextKey
  1006. }
  1007. // GetLanguageInputContextKey returns the LanguageInputContextKey field.
  1008. func (c *Configuration) GetLanguageInputContextKey() string {
  1009. return c.LanguageInputContextKey
  1010. }
  1011. // GetVersionContextKey returns the VersionContextKey field.
  1012. func (c *Configuration) GetVersionContextKey() string {
  1013. return c.VersionContextKey
  1014. }
  1015. // GetVersionAliasesContextKey returns the VersionAliasesContextKey field.
  1016. func (c *Configuration) GetVersionAliasesContextKey() string {
  1017. return c.VersionAliasesContextKey
  1018. }
  1019. // GetViewEngineContextKey returns the ViewEngineContextKey field.
  1020. func (c *Configuration) GetViewEngineContextKey() string {
  1021. return c.ViewEngineContextKey
  1022. }
  1023. // GetViewLayoutContextKey returns the ViewLayoutContextKey field.
  1024. func (c *Configuration) GetViewLayoutContextKey() string {
  1025. return c.ViewLayoutContextKey
  1026. }
  1027. // GetViewDataContextKey returns the ViewDataContextKey field.
  1028. func (c *Configuration) GetViewDataContextKey() string {
  1029. return c.ViewDataContextKey
  1030. }
  1031. // GetFallbackViewContextKey returns the FallbackViewContextKey field.
  1032. func (c *Configuration) GetFallbackViewContextKey() string {
  1033. return c.FallbackViewContextKey
  1034. }
  1035. // GetRemoteAddrHeaders returns the RemoteAddrHeaders field.
  1036. func (c *Configuration) GetRemoteAddrHeaders() []string {
  1037. return c.RemoteAddrHeaders
  1038. }
  1039. // GetRemoteAddrHeadersForce returns RemoteAddrHeadersForce field.
  1040. func (c *Configuration) GetRemoteAddrHeadersForce() bool {
  1041. return c.RemoteAddrHeadersForce
  1042. }
  1043. // GetSSLProxyHeaders returns the SSLProxyHeaders field.
  1044. func (c *Configuration) GetSSLProxyHeaders() map[string]string {
  1045. return c.SSLProxyHeaders
  1046. }
  1047. // GetRemoteAddrPrivateSubnets returns the RemoteAddrPrivateSubnets field.
  1048. func (c *Configuration) GetRemoteAddrPrivateSubnets() []netutil.IPRange {
  1049. return c.RemoteAddrPrivateSubnets
  1050. }
  1051. // GetHostProxyHeaders returns the HostProxyHeaders field.
  1052. func (c *Configuration) GetHostProxyHeaders() map[string]bool {
  1053. return c.HostProxyHeaders
  1054. }
  1055. // GetOther returns the Other field.
  1056. func (c *Configuration) GetOther() map[string]interface{} {
  1057. return c.Other
  1058. }
  1059. // WithConfiguration sets the "c" values to the framework's configurations.
  1060. //
  1061. // Usage:
  1062. // app.Listen(":8080", iris.WithConfiguration(iris.Configuration{/* fields here */ }))
  1063. // or
  1064. // iris.WithConfiguration(iris.YAML("./cfg/iris.yml"))
  1065. // or
  1066. // iris.WithConfiguration(iris.TOML("./cfg/iris.tml"))
  1067. func WithConfiguration(c Configuration) Configurator {
  1068. return func(app *Application) {
  1069. main := app.config
  1070. if main == nil {
  1071. app.config = &c
  1072. return
  1073. }
  1074. if v := c.LogLevel; v != "" {
  1075. main.LogLevel = v
  1076. }
  1077. if v := c.SocketSharding; v {
  1078. main.SocketSharding = v
  1079. }
  1080. if v := c.KeepAlive; v > 0 {
  1081. main.KeepAlive = v
  1082. }
  1083. if v := c.Timeout; v > 0 {
  1084. main.Timeout = v
  1085. }
  1086. if v := c.TimeoutMessage; v != "" {
  1087. main.TimeoutMessage = v
  1088. }
  1089. if v := c.NonBlocking; v {
  1090. main.NonBlocking = v
  1091. }
  1092. if len(c.Tunneling.Tunnels) > 0 {
  1093. main.Tunneling = c.Tunneling
  1094. }
  1095. if v := c.IgnoreServerErrors; len(v) > 0 {
  1096. main.IgnoreServerErrors = append(main.IgnoreServerErrors, v...)
  1097. }
  1098. if v := c.DisableStartupLog; v {
  1099. main.DisableStartupLog = v
  1100. }
  1101. if v := c.DisableInterruptHandler; v {
  1102. main.DisableInterruptHandler = v
  1103. }
  1104. if v := c.DisablePathCorrection; v {
  1105. main.DisablePathCorrection = v
  1106. }
  1107. if v := c.DisablePathCorrectionRedirection; v {
  1108. main.DisablePathCorrectionRedirection = v
  1109. }
  1110. if v := c.EnablePathIntelligence; v {
  1111. main.EnablePathIntelligence = v
  1112. }
  1113. if v := c.EnablePathEscape; v {
  1114. main.EnablePathEscape = v
  1115. }
  1116. if v := c.ForceLowercaseRouting; v {
  1117. main.ForceLowercaseRouting = v
  1118. }
  1119. if v := c.EnableOptimizations; v {
  1120. main.EnableOptimizations = v
  1121. }
  1122. if v := c.EnableProtoJSON; v {
  1123. main.EnableProtoJSON = v
  1124. }
  1125. if v := c.EnableEasyJSON; v {
  1126. main.EnableEasyJSON = v
  1127. }
  1128. if v := c.FireMethodNotAllowed; v {
  1129. main.FireMethodNotAllowed = v
  1130. }
  1131. if v := c.DisableAutoFireStatusCode; v {
  1132. main.DisableAutoFireStatusCode = v
  1133. }
  1134. if v := c.ResetOnFireErrorCode; v {
  1135. main.ResetOnFireErrorCode = v
  1136. }
  1137. if v := c.URLParamSeparator; v != nil {
  1138. main.URLParamSeparator = v
  1139. }
  1140. if v := c.DisableBodyConsumptionOnUnmarshal; v {
  1141. main.DisableBodyConsumptionOnUnmarshal = v
  1142. }
  1143. if v := c.FireEmptyFormError; v {
  1144. main.FireEmptyFormError = v
  1145. }
  1146. if v := c.TimeFormat; v != "" {
  1147. main.TimeFormat = v
  1148. }
  1149. if v := c.Charset; v != "" {
  1150. main.Charset = v
  1151. }
  1152. if v := c.PostMaxMemory; v > 0 {
  1153. main.PostMaxMemory = v
  1154. }
  1155. if v := c.LocaleContextKey; v != "" {
  1156. main.LocaleContextKey = v
  1157. }
  1158. if v := c.LanguageContextKey; v != "" {
  1159. main.LanguageContextKey = v
  1160. }
  1161. if v := c.LanguageInputContextKey; v != "" {
  1162. main.LanguageInputContextKey = v
  1163. }
  1164. if v := c.VersionContextKey; v != "" {
  1165. main.VersionContextKey = v
  1166. }
  1167. if v := c.VersionAliasesContextKey; v != "" {
  1168. main.VersionAliasesContextKey = v
  1169. }
  1170. if v := c.ViewEngineContextKey; v != "" {
  1171. main.ViewEngineContextKey = v
  1172. }
  1173. if v := c.ViewLayoutContextKey; v != "" {
  1174. main.ViewLayoutContextKey = v
  1175. }
  1176. if v := c.ViewDataContextKey; v != "" {
  1177. main.ViewDataContextKey = v
  1178. }
  1179. if v := c.FallbackViewContextKey; v != "" {
  1180. main.FallbackViewContextKey = v
  1181. }
  1182. if v := c.RemoteAddrHeaders; len(v) > 0 {
  1183. main.RemoteAddrHeaders = v
  1184. }
  1185. if v := c.RemoteAddrHeadersForce; v {
  1186. main.RemoteAddrHeadersForce = v
  1187. }
  1188. if v := c.RemoteAddrPrivateSubnets; len(v) > 0 {
  1189. main.RemoteAddrPrivateSubnets = v
  1190. }
  1191. if v := c.SSLProxyHeaders; len(v) > 0 {
  1192. if main.SSLProxyHeaders == nil {
  1193. main.SSLProxyHeaders = make(map[string]string, len(v))
  1194. }
  1195. for key, value := range v {
  1196. main.SSLProxyHeaders[key] = value
  1197. }
  1198. }
  1199. if v := c.HostProxyHeaders; len(v) > 0 {
  1200. if main.HostProxyHeaders == nil {
  1201. main.HostProxyHeaders = make(map[string]bool, len(v))
  1202. }
  1203. for key, value := range v {
  1204. main.HostProxyHeaders[key] = value
  1205. }
  1206. }
  1207. if v := c.Other; len(v) > 0 {
  1208. if main.Other == nil {
  1209. main.Other = make(map[string]interface{}, len(v))
  1210. }
  1211. for key, value := range v {
  1212. main.Other[key] = value
  1213. }
  1214. }
  1215. }
  1216. }
  1217. // DefaultTimeoutMessage is the default timeout message which is rendered
  1218. // on expired handlers when timeout handler is registered (see Timeout configuration field).
  1219. var DefaultTimeoutMessage = `<html><head><title>Timeout</title></head><body><h1>Timeout</h1>Looks like the server is taking too long to respond, this can be caused by either poor connectivity or an error with our servers. Please try again in a while.</body></html>`
  1220. func toStringPtr(s string) *string {
  1221. return &s
  1222. }
  1223. // DefaultConfiguration returns the default configuration for an iris station, fills the main Configuration
  1224. func DefaultConfiguration() Configuration {
  1225. return Configuration{
  1226. LogLevel: "info",
  1227. SocketSharding: false,
  1228. KeepAlive: 0,
  1229. Timeout: 0,
  1230. TimeoutMessage: DefaultTimeoutMessage,
  1231. NonBlocking: false,
  1232. DisableStartupLog: false,
  1233. DisableInterruptHandler: false,
  1234. DisablePathCorrection: false,
  1235. EnablePathEscape: false,
  1236. ForceLowercaseRouting: false,
  1237. FireMethodNotAllowed: false,
  1238. DisableBodyConsumptionOnUnmarshal: false,
  1239. FireEmptyFormError: false,
  1240. DisableAutoFireStatusCode: false,
  1241. ResetOnFireErrorCode: false,
  1242. URLParamSeparator: toStringPtr(","),
  1243. TimeFormat: "Mon, 02 Jan 2006 15:04:05 GMT",
  1244. Charset: "utf-8",
  1245. // PostMaxMemory is for post body max memory.
  1246. //
  1247. // The request body the size limit
  1248. // can be set by the middleware `LimitRequestBodySize`
  1249. // or `context#SetMaxRequestBodySize`.
  1250. PostMaxMemory: 32 << 20, // 32MB
  1251. LocaleContextKey: "iris.locale",
  1252. LanguageContextKey: "iris.locale.language",
  1253. LanguageInputContextKey: "iris.locale.language.input",
  1254. VersionContextKey: "iris.api.version",
  1255. VersionAliasesContextKey: "iris.api.version.aliases",
  1256. ViewEngineContextKey: "iris.view.engine",
  1257. ViewLayoutContextKey: "iris.view.layout",
  1258. ViewDataContextKey: "iris.view.data",
  1259. FallbackViewContextKey: "iris.view.fallback",
  1260. RemoteAddrHeaders: nil,
  1261. RemoteAddrHeadersForce: false,
  1262. RemoteAddrPrivateSubnets: []netutil.IPRange{
  1263. {
  1264. Start: "10.0.0.0",
  1265. End: "10.255.255.255",
  1266. },
  1267. {
  1268. Start: "100.64.0.0",
  1269. End: "100.127.255.255",
  1270. },
  1271. {
  1272. Start: "172.16.0.0",
  1273. End: "172.31.255.255",
  1274. },
  1275. {
  1276. Start: "192.0.0.0",
  1277. End: "192.0.0.255",
  1278. },
  1279. {
  1280. Start: "192.168.0.0",
  1281. End: "192.168.255.255",
  1282. },
  1283. {
  1284. Start: "198.18.0.0",
  1285. End: "198.19.255.255",
  1286. },
  1287. },
  1288. SSLProxyHeaders: make(map[string]string),
  1289. HostProxyHeaders: make(map[string]bool),
  1290. EnableOptimizations: false,
  1291. EnableProtoJSON: false,
  1292. EnableEasyJSON: false,
  1293. Other: make(map[string]interface{}),
  1294. }
  1295. }