Configuration
At the Host section we've learnt about the first input argument of the app.Run, here we will take a look of what the second one is.
Let's start from basics. The iris.New function returns an iris.Application. This Application value can be configured through its Configure(...iris.Configurator) and Run methods.
The second optional, varadiac argument of app.Run/Listen method accepts one or more iris.Configurator. An iris.Configurator is just a type of: func(app *iris.Application). Custom iris.Configurator can be passed to modify yours *iris.Application as well.
There are built-iniris.Configurators for each of the core Configuration's fields, such as iris.WithoutStartupLog, iris.WithCharset("UTF-8"), iris.WithOptimizations and iris.WithConfiguration(iris.Configuration{...}) functions.
Each "module" like the iris view engine, websockets, sessions and each middleware has its own configurations and options.

Using the Configuration

All of the iris.Configuration fields are defaulted to the most common use cases. If you want to make use of a custom iris.Configurator at any point call the app.Configure(accepts iris.Configurator) method to pass your configurator(s) there.
1
config := iris.WithConfiguration(iris.Configuration {
2
DisableStartupLog: true,
3
Optimizations: true,
4
Charset: "UTF-8",
5
})
6
7
app.Listen(":8080", config)
Copied!
List of all available settings:
1
// Tunnel is the Tunnels field of the TunnelingConfiguration structure.
2
type Tunnel struct {
3
// Name is the only one required field,
4
// it is used to create and close tunnels, e.g. "MyApp".
5
// If this field is not empty then ngrok tunnels will be created
6
// when the iris app is up and running.
7
Name string `json:"name" yaml:"Name" toml:"Name"`
8
// Addr is basically optionally as it will be set through
9
// Iris built-in Runners, however, if `iris.Raw` is used
10
// then this field should be set of form 'hostname:port'
11
// because framework cannot be aware
12
// of the address you used to run the server on this custom runner.
13
Addr string `json:"addr,omitempty" yaml:"Addr" toml:"Addr"`
14
}
15
16
// TunnelingConfiguration contains configuration
17
// for the optional tunneling through ngrok feature.
18
// Note that the ngrok should be already installed at the host machine.
19
type TunnelingConfiguration struct {
20
// AuthToken field is optionally and can be used
21
// to authenticate the ngrok access.
22
// ngrok authtoken <YOUR_AUTHTOKEN>
23
AuthToken string `json:"authToken,omitempty" yaml:"AuthToken" toml:"AuthToken"`
24
25
// No...
26
// Config is optionally and can be used
27
// to load ngrok configuration from file system path.
28
//
29
// If you don't specify a location for a configuration file,
30
// ngrok tries to read one from the default location $HOME/.ngrok2/ngrok.yml.
31
// The configuration file is optional; no error is emitted if that path does not exist.
32
// Config string `json:"config,omitempty" yaml:"Config" toml:"Config"`
33
34
// Bin is the system binary path of the ngrok executable file.
35
// If it's empty then the framework will try to find it through system env variables.
36
Bin string `json:"bin,omitempty" yaml:"Bin" toml:"Bin"`
37
38
// WebUIAddr is the web interface address of an already-running ngrok instance.
39
// Iris will try to fetch the default web interface address(http://127.0.0.1:4040)
40
// to determinate if a ngrok instance is running before try to start it manually.
41
// However if a custom web interface address is used,
42
// this field must be set e.g. http://127.0.0.1:5050.
43
WebInterface string `json:"webInterface,omitempty" yaml:"WebInterface" toml:"WebInterface"`
44
45
// Region is optionally, can be used to set the region which defaults to "us".
46
// Available values are:
47
// "us" for United States
48
// "eu" for Europe
49
// "ap" for Asia/Pacific
50
// "au" for Australia
51
// "sa" for South America
52
// "jp" forJapan
53
// "in" for India
54
Region string `json:"region,omitempty" yaml:"Region" toml:"Region"`
55
56
// Tunnels the collection of the tunnels.
57
// One tunnel per Iris Host per Application, usually you only need one.
58
Tunnels []Tunnel `json:"tunnels" yaml:"Tunnels" toml:"Tunnels"`
59
}
60
61
// Configuration holds the necessary settings for an Iris Application instance.
62
// All fields are optionally, the default values will work for a common web application.
63
//
64
// A Configuration value can be passed through `WithConfiguration` Configurator.
65
// Usage:
66
// conf := iris.Configuration{ ... }
67
// app := iris.New()
68
// app.Configure(iris.WithConfiguration(conf)) OR
69
// app.Run/Listen(..., iris.WithConfiguration(conf)).
70
type Configuration struct {
71
// LogLevel is the log level the application should use to output messages.
72
// Logger, by default, is mostly used on Build state but it is also possible
73
// that debug error messages could be thrown when the app is running, e.g.
74
// when malformed data structures try to be sent on Client (i.e Context.JSON/JSONP/XML...).
75
//
76
// Defaults to "info". Possible values are:
77
// * "disable"
78
// * "fatal"
79
// * "error"
80
// * "warn"
81
// * "info"
82
// * "debug"
83
LogLevel string `json:"logLevel" yaml:"LogLevel" toml:"LogLevel" env:"LOG_LEVEL"`
84
85
// Tunneling can be optionally set to enable ngrok http(s) tunneling for this Iris app instance.
86
// See the `WithTunneling` Configurator too.
87
Tunneling TunnelingConfiguration `json:"tunneling,omitempty" yaml:"Tunneling" toml:"Tunneling"`
88
89
// IgnoreServerErrors will cause to ignore the matched "errors"
90
// from the main application's `Run` function.
91
// This is a slice of string, not a slice of error
92
// users can register these errors using yaml or toml configuration file
93
// like the rest of the configuration fields.
94
//
95
// See `WithoutServerError(...)` function too.
96
//
97
// Example: https://github.com/kataras/iris/tree/master/_examples/http-server/listen-addr/omit-server-errors
98
//
99
// Defaults to an empty slice.
100
IgnoreServerErrors []string `json:"ignoreServerErrors,omitempty" yaml:"IgnoreServerErrors" toml:"IgnoreServerErrors"`
101
102
// DisableStartupLog if set to true then it turns off the write banner on server startup.
103
//
104
// Defaults to false.
105
DisableStartupLog bool `json:"disableStartupLog,omitempty" yaml:"DisableStartupLog" toml:"DisableStartupLog"`
106
// DisableInterruptHandler if set to true then it disables the automatic graceful server shutdown
107
// when control/cmd+C pressed.
108
// Turn this to true if you're planning to handle this by your own via a custom host.Task.
109
//
110
// Defaults to false.
111
DisableInterruptHandler bool `json:"disableInterruptHandler,omitempty" yaml:"DisableInterruptHandler" toml:"DisableInterruptHandler"`
112
113
// DisablePathCorrection disables the correcting
114
// and redirecting or executing directly the handler of
115
// the requested path to the registered path
116
// for example, if /home/ path is requested but no handler for this Route found,
117
// then the Router checks if /home handler exists, if yes,
118
// (permanent)redirects the client to the correct path /home.
119
//
120
// See `DisablePathCorrectionRedirection` to enable direct handler execution instead of redirection.
121
//
122
// Defaults to false.
123
DisablePathCorrection bool `json:"disablePathCorrection,omitempty" yaml:"DisablePathCorrection" toml:"DisablePathCorrection"`
124
// DisablePathCorrectionRedirection works whenever configuration.DisablePathCorrection is set to false
125
// and if DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without
126
// the trailing slash ("/") instead of send a redirection status.
127
//
128
// Defaults to false.
129
DisablePathCorrectionRedirection bool `json:"disablePathCorrectionRedirection,omitempty" yaml:"DisablePathCorrectionRedirection" toml:"DisablePathCorrectionRedirection"`
130
// EnablePathIntelligence if set to true,
131
// the router will redirect HTTP "GET" not found pages to the most closest one path(if any). For example
132
// you register a route at "/contact" path -
133
// a client tries to reach it by "/cont", the path will be automatic fixed
134
// and the client will be redirected to the "/contact" path
135
// instead of getting a 404 not found response back.
136
//
137
// Defaults to false.
138
EnablePathIntelligence bool `json:"enablePathIntelligence,omitempty" yaml:"EnablePathIntelligence" toml:"EnablePathIntelligence"`
139
// EnablePathEscape when is true then its escapes the path and the named parameters (if any).
140
// When do you need to Disable(false) it:
141
// accepts parameters with slash '/'
142
// Request: http://localhost:8080/details/Project%2FDelta
143
// ctx.Param("project") returns the raw named parameter: Project%2FDelta
144
// which you can escape it manually with net/url:
145
// projectName, _ := url.QueryUnescape(c.Param("project").
146
//
147
// Defaults to false.
148
EnablePathEscape bool `json:"enablePathEscape,omitempty" yaml:"EnablePathEscape" toml:"EnablePathEscape"`
149
// ForceLowercaseRouting if enabled, converts all registered routes paths to lowercase
150
// and it does lowercase the request path too for matching.
151
//
152
// Defaults to false.
153
ForceLowercaseRouting bool `json:"forceLowercaseRouting,omitempty" yaml:"ForceLowercaseRouting" toml:"ForceLowercaseRouting"`
154
// FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and
155
// fires the 405 error instead of 404
156
// Defaults to false.
157
FireMethodNotAllowed bool `json:"fireMethodNotAllowed,omitempty" yaml:"FireMethodNotAllowed" toml:"FireMethodNotAllowed"`
158
// DisableAutoFireStatusCode if true then it turns off the http error status code
159
// handler automatic execution on error code from a `Context.StatusCode` call.
160
// By-default a custom http error handler will be fired when "Context.StatusCode(errorCode)" called.
161
//
162
// Defaults to false.
163
DisableAutoFireStatusCode bool `json:"disableAutoFireStatusCode,omitempty" yaml:"DisableAutoFireStatusCode" toml:"DisableAutoFireStatusCode"`
164
// ResetOnFireErrorCode if true then any previously response body or headers through
165
// response recorder or gzip writer will be ignored and the router
166
// will fire the registered (or default) HTTP error handler instead.
167
// See `core/router/handler#FireErrorCode` and `Context.EndRequest` for more details.
168
//
169
// Read more at: https://github.com/kataras/iris/issues/1531
170
//
171
// Defaults to false.
172
ResetOnFireErrorCode bool `json:"resetOnFireErrorCode,omitempty" yaml:"ResetOnFireErrorCode" toml:"ResetOnFireErrorCode"`
173
174
// EnableOptimization when this field is true
175
// then the application tries to optimize for the best performance where is possible.
176
//
177
// Defaults to false.
178
EnableOptimizations bool `json:"enableOptimizations,omitempty" yaml:"EnableOptimizations" toml:"EnableOptimizations"`
179
// DisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
180
// If set to true then it
181
// disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`.
182
//
183
// By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`,
184
// if this field set to true then a new buffer will be created to read from and the request body.
185
// The body will not be changed and existing data before the
186
// context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.
187
DisableBodyConsumptionOnUnmarshal bool `json:"disableBodyConsumptionOnUnmarshal,omitempty" yaml:"DisableBodyConsumptionOnUnmarshal" toml:"DisableBodyConsumptionOnUnmarshal"`
188
// FireEmptyFormError returns if set to tue true then the `context.ReadBody/ReadForm`
189
// will return an `iris.ErrEmptyForm` on empty request form data.
190
FireEmptyFormError bool `json:"fireEmptyFormError,omitempty" yaml:"FireEmptyFormError" yaml:"FireEmptyFormError"`
191
192
// TimeFormat time format for any kind of datetime parsing
193
// Defaults to "Mon, 02 Jan 2006 15:04:05 GMT".
194
TimeFormat string `json:"timeFormat,omitempty" yaml:"TimeFormat" toml:"TimeFormat"`
195
196
// Charset character encoding for various rendering
197
// used for templates and the rest of the responses
198
// Defaults to "utf-8".
199
Charset string `json:"charset,omitempty" yaml:"Charset" toml:"Charset"`
200
201
// PostMaxMemory sets the maximum post data size
202
// that a client can send to the server, this differs
203
// from the overral request body size which can be modified
204
// by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
205
//
206
// Defaults to 32MB or 32 << 20 if you prefer.
207
PostMaxMemory int64 `json:"postMaxMemory" yaml:"PostMaxMemory" toml:"PostMaxMemory"`
208
// +----------------------------------------------------+
209
// | Context's keys for values used on various featuers |
210
// +----------------------------------------------------+
211
212
// Context values' keys for various features.
213
//
214
// LocaleContextKey is used by i18n to get the current request's locale, which contains a translate function too.
215
//
216
// Defaults to "iris.locale".
217
LocaleContextKey string `json:"localeContextKey,omitempty" yaml:"LocaleContextKey" toml:"LocaleContextKey"`
218
// LanguageContextKey is the context key which a language can be modified by a middleware.
219
// It has the highest priority over the rest and if it is empty then it is ignored,
220
// if it set to a static string of "default" or to the default language's code
221
// then the rest of the language extractors will not be called at all and
222
// the default language will be set instead.
223
//
224
// Use with `Context.SetLanguage("el-GR")`.
225
//
226
// See `i18n.ExtractFunc` for a more organised way of the same feature.
227
// Defaults to "iris.locale.language".
228
LanguageContextKey string `json:"languageContextKey,omitempty" yaml:"LanguageContextKey" toml:"LanguageContextKey"`
229
// VersionContextKey is the context key which an API Version can be modified
230
// via a middleware through `SetVersion` method, e.g. `ctx.SetVersion("1.0, 1.1")`.
231
// Defaults to "iris.api.version".
232
VersionContextKey string `json:"versionContextKey" yaml:"VersionContextKey" toml:"VersionContextKey"`
233
// GetViewLayoutContextKey is the key of the context's user values' key
234
// which is being used to set the template
235
// layout from a middleware or the main handler.
236
// Overrides the parent's or the configuration's.
237
//
238
// Defaults to "iris.ViewLayout"
239
ViewLayoutContextKey string `json:"viewLayoutContextKey,omitempty" yaml:"ViewLayoutContextKey" toml:"ViewLayoutContextKey"`
240
// GetViewDataContextKey is the key of the context's user values' key
241
// which is being used to set the template
242
// binding data from a middleware or the main handler.
243
//
244
// Defaults to "iris.viewData"
245
ViewDataContextKey string `json:"viewDataContextKey,omitempty" yaml:"ViewDataContextKey" toml:"ViewDataContextKey"`
246
// RemoteAddrHeaders are the allowed request headers names
247
// that can be valid to parse the client's IP based on.
248
// By-default no "X-" header is consired safe to be used for retrieving the
249
// client's IP address, because those headers can manually change by
250
// the client. But sometimes are useful e.g., when behind a proxy
251
// you want to enable the "X-Forwarded-For" or when cloudflare
252
// you want to enable the "CF-Connecting-IP", inneed you
253
// can allow the `ctx.RemoteAddr()` to use any header
254
// that the client may sent.
255
//
256
// Defaults to an empty map but an example usage is:
257
// RemoteAddrHeaders {
258
// "X-Real-Ip": true,
259
// "X-Forwarded-For": true,
260
// "CF-Connecting-IP": true,
261
// }
262
//
263
// Look `context.RemoteAddr()` for more.
264
RemoteAddrHeaders map[string]bool `json:"remoteAddrHeaders,omitempty" yaml:"RemoteAddrHeaders" toml:"RemoteAddrHeaders"`
265
// RemoteAddrPrivateSubnets defines the private sub-networks.
266
// They are used to be compared against
267
// IP Addresses fetched through `RemoteAddrHeaders` or `Context.Request.RemoteAddr`.
268
// For details please navigate through: https://github.com/kataras/iris/issues/1453
269
// Defaults to:
270
// {
271
// Start: net.ParseIP("10.0.0.0"),
272
// End: net.ParseIP("10.255.255.255"),
273
// },
274
// {
275
// Start: net.ParseIP("100.64.0.0"),
276
// End: net.ParseIP("100.127.255.255"),
277
// },
278
// {
279
// Start: net.ParseIP("172.16.0.0"),
280
// End: net.ParseIP("172.31.255.255"),
281
// },
282
// {
283
// Start: net.ParseIP("192.0.0.0"),
284
// End: net.ParseIP("192.0.0.255"),
285
// },
286
// {
287
// Start: net.ParseIP("192.168.0.0"),
288
// End: net.ParseIP("192.168.255.255"),
289
// },
290
// {
291
// Start: net.ParseIP("198.18.0.0"),
292
// End: net.ParseIP("198.19.255.255"),
293
// }
294
//
295
// Look `Context.RemoteAddr()` for more.
296
RemoteAddrPrivateSubnets []netutil.IPRange `json:"remoteAddrPrivateSubnets" yaml:"RemoteAddrPrivateSubnets" toml:"RemoteAddrPrivateSubnets"`
297
// SSLProxyHeaders defines the set of header key values
298
// that would indicate a valid https Request (look `Context.IsSSL()`).
299
// Example: `map[string]string{"X-Forwarded-Proto": "https"}`.
300
//
301
// Defaults to empty map.
302
SSLProxyHeaders map[string]string `json:"sslProxyHeaders" yaml:"SSLProxyHeaders" toml:"SSLProxyHeaders"`
303
// HostProxyHeaders defines the set of headers that may hold a proxied hostname value for the clients.
304
// Look `Context.Host()` for more.
305
// Defaults to empty map.
306
HostProxyHeaders map[string]bool `json:"hostProxyHeaders" yaml:"HostProxyHeaders" toml:"HostProxyHeaders"`
307
// Other are the custom, dynamic options, can be empty.
308
// This field used only by you to set any app's options you want.
309
//
310
// Defaults to empty map.
311
Other map[string]interface{} `json:"other,omitempty" yaml:"Other" toml:"Other"`
312
}
Copied!

Load from YAML

Using the iris.YAML("path").
File: iris.yml
1
FireMethodNotAllowed: true
2
DisableBodyConsumptionOnUnmarshal: true
3
TimeFormat: Mon, 01 Jan 2006 15:04:05 GMT
4
Charset: UTF-8
Copied!
File: main.go
1
config := iris.WithConfiguration(iris.YAML("./iris.yml"))
2
app.Listen(":8080", config)
Copied!

Load from TOML

Using the iris.TOML("path").
File: iris.tml
1
FireMethodNotAllowed = true
2
DisableBodyConsumptionOnUnmarshal = false
3
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
4
Charset = "UTF-8"
5
6
[Other]
7
ServerName = "my fancy iris server"
8
ServerOwner = "[email protected]"
Copied!
File: main.go
1
config := iris.WithConfiguration(iris.TOML("./iris.tml"))
2
app.Listen(":8080", config)
Copied!

Using the functional way

As we already mention, you can pass any number of iris.Configurator in the app.Run/Listen’s second argument. Iris provides an option for each of its iris.Configuration’s fields.
1
app.Listen(":8080", iris.WithoutInterruptHandler,
2
iris.WithoutBodyConsumptionOnUnmarshal,
3
iris.WithoutAutoFireStatusCode,
4
iris.WithLowercaseRouting,
5
iris.WithPathIntelligence,
6
iris.WithOptimizations,
7
iris.WithTimeFormat("Mon, 01 Jan 2006 15:04:05 GMT"),
8
)
Copied!
Good when you want to change some of the configuration's field. Prefix: "With" or "Without", code editors will help you navigate through all configuration options without even a glitch to the documentation.
List of functional options:
1
var (
2
WithGlobalConfiguration Configurator
3
WithoutStartupLog, WithoutBanner Configurator
4
WithoutInterruptHandler Configurator
5
WithoutPathCorrection Configurator
6
WithPathIntelligence Configurator
7
WithoutPathCorrectionRedirection Configurator
8
WithoutBodyConsumptionOnUnmarshal Configurator
9
WithEmptyFormError Configurator
10
WithPathEscape Configurator
11
WithLowercaseRouting Configurator
12
WithOptimizations Configurator
13
WithFireMethodNotAllowed Configurator
14
WithoutAutoFireStatusCode Configurator
15
WithResetOnFireErrorCode Configurator
16
WithTunneling Configurator
17
)
18
19
func WithLogLevel(level string) Configurator
20
func WithoutServerError(errors ...error) Configurator
21
func WithTimeFormat(timeformat string) Configurator
22
func WithCharset(charset string) Configurator
23
func WithPostMaxMemory(limit int64) Configurator
24
func WithRemoteAddrHeader(header ...string) Configurator
25
func WithoutRemoteAddrHeader(headerName string) Configurator
26
func WithRemoteAddrPrivateSubnet(startIP, endIP string) Configurator
27
func WithSSLProxyHeader(headerKey, headerValue string) Configurator
28
func WithHostProxyHeader(headers ...string) Configurator
29
func WithOtherValue(key string, val interface{}) Configurator
30
func WithSitemap(startURL string) Configurator
Copied!

Custom values

The iris.Configuration contains a field named Other map[string]interface{} which accepts any custom key:value option, therefore you can use that field to pass specific values that your app expects based on the custom requirements.
1
app.Listen(":8080",
2
iris.WithOtherValue("ServerName", "my amazing iris server"),
3
iris.WithOtherValue("ServerOwner", "[email protected]"),
4
)
Copied!
You can access those fields via app.ConfigurationReadOnly.

Access Configuration from Context

1
func (ctx iris.Context) {
2
cfg := app.Application().ConfigurationReadOnly().GetOther()
3
srvName := cfg["MyServerName"]
4
srvOwner := cfg["ServerOwner"]
5
}
Copied!
Last modified 1yr ago