0
# Headers Management
1
2
Comprehensive header management with immutable collections, builder patterns, and standard HTTP header constants.
3
4
## Capabilities
5
6
### Headers Interface
7
8
Immutable collection of HTTP headers extending StringValues for key-value access.
9
10
```kotlin { .api }
11
/**
12
* Immutable collection of HTTP headers
13
*/
14
interface Headers : StringValues {
15
companion object {
16
val Empty: Headers
17
18
/**
19
* Build headers using a builder function
20
* @param builder Function to configure headers
21
* @return Immutable Headers instance
22
*/
23
fun build(builder: HeadersBuilder.() -> Unit): Headers
24
}
25
}
26
```
27
28
### Headers Builder
29
30
Mutable builder for constructing Headers instances.
31
32
```kotlin { .api }
33
/**
34
* Mutable builder for HTTP headers
35
*/
36
class HeadersBuilder : StringValuesBuilderImpl() {
37
/**
38
* Append a header value (allows multiple values for same header)
39
* @param name Header name
40
* @param value Header value
41
*/
42
fun append(name: String, value: String)
43
44
/**
45
* Set a header value (replaces existing values)
46
* @param name Header name
47
* @param value Header value
48
*/
49
fun set(name: String, value: String)
50
51
/**
52
* Remove all values for a header
53
* @param name Header name
54
*/
55
fun remove(name: String)
56
57
/**
58
* Build immutable Headers instance
59
* @return Headers containing all added headers
60
*/
61
fun build(): Headers
62
}
63
```
64
65
### Standard HTTP Headers
66
67
Constants for all standard HTTP header names with validation utilities.
68
69
```kotlin { .api }
70
/**
71
* Standard HTTP header names
72
*/
73
object HttpHeaders {
74
// Request headers
75
val Accept: String
76
val AcceptCharset: String
77
val AcceptEncoding: String
78
val AcceptLanguage: String
79
val Authorization: String
80
val CacheControl: String
81
val Connection: String
82
val Cookie: String
83
val ContentLength: String
84
val ContentType: String
85
val Date: String
86
val Expect: String
87
val From: String
88
val Host: String
89
val IfMatch: String
90
val IfModifiedSince: String
91
val IfNoneMatch: String
92
val IfRange: String
93
val IfUnmodifiedSince: String
94
val MaxForwards: String
95
val Origin: String
96
val Pragma: String
97
val ProxyAuthorization: String
98
val Range: String
99
val Referrer: String
100
val TE: String
101
val Upgrade: String
102
val UserAgent: String
103
val Via: String
104
val Warning: String
105
106
// Response headers
107
val AcceptRanges: String
108
val Age: String
109
val Allow: String
110
val ContentDisposition: String
111
val ContentEncoding: String
112
val ContentLanguage: String
113
val ContentLocation: String
114
val ContentRange: String
115
val ETag: String
116
val Expires: String
117
val LastModified: String
118
val Link: String
119
val Location: String
120
val ProxyAuthenticate: String
121
val RetryAfter: String
122
val Server: String
123
val SetCookie: String
124
val Trailer: String
125
val TransferEncoding: String
126
val Vary: String
127
val WWWAuthenticate: String
128
129
// CORS headers
130
val AccessControlAllowCredentials: String
131
val AccessControlAllowHeaders: String
132
val AccessControlAllowMethods: String
133
val AccessControlAllowOrigin: String
134
val AccessControlExposeHeaders: String
135
val AccessControlMaxAge: String
136
val AccessControlRequestHeaders: String
137
val AccessControlRequestMethod: String
138
139
// Security headers
140
val StrictTransportSecurity: String
141
val PublicKeyPins: String
142
val PublicKeyPinsReportOnly: String
143
144
// WebSocket headers
145
val SecWebSocketAccept: String
146
val SecWebSocketExtensions: String
147
val SecWebSocketKey: String
148
val SecWebSocketProtocol: String
149
val SecWebSocketVersion: String
150
151
// Custom headers
152
val XCorrelationId: String
153
val XForwardedFor: String
154
val XForwardedHost: String
155
val XForwardedPort: String
156
val XForwardedProto: String
157
val XForwardedServer: String
158
val XHttpMethodOverride: String
159
val XRequestId: String
160
val XTotalCount: String
161
162
// Additional WebDAV headers
163
val DASL: String
164
val DAV: String
165
val Depth: String
166
val Destination: String
167
val If: String
168
val LockToken: String
169
val Overwrite: String
170
val Timeout: String
171
172
val UnsafeHeaders: Array<String>
173
val UnsafeHeadersList: List<String>
174
175
/**
176
* Validate header name according to HTTP specification
177
* @param name Header name to validate
178
* @throws IllegalHeaderNameException if invalid
179
*/
180
fun checkHeaderName(name: String)
181
182
/**
183
* Validate header value according to HTTP specification
184
* @param value Header value to validate
185
* @throws IllegalHeaderValueException if invalid
186
*/
187
fun checkHeaderValue(value: String)
188
189
/**
190
* Check if header name is considered unsafe for browser requests
191
* @param name Header name to check
192
* @return true if header is unsafe
193
*/
194
fun isUnsafe(name: String): Boolean
195
}
196
```
197
198
### Header Construction Utilities
199
200
Utility functions for creating Headers instances.
201
202
```kotlin { .api }
203
/**
204
* Create headers using builder function
205
* @param builder Function to configure headers
206
* @return Headers instance
207
*/
208
fun headers(builder: HeadersBuilder.() -> Unit): Headers
209
210
/**
211
* Create empty headers
212
* @return Empty Headers instance
213
*/
214
fun headersOf(): Headers
215
216
/**
217
* Create headers with single name-value pair
218
* @param name Header name
219
* @param value Header value
220
* @return Headers instance
221
*/
222
fun headersOf(name: String, value: String): Headers
223
224
/**
225
* Create headers with single name and multiple values
226
* @param name Header name
227
* @param values List of header values
228
* @return Headers instance
229
*/
230
fun headersOf(name: String, values: List<String>): Headers
231
232
/**
233
* Create headers from pairs
234
* @param pairs Variable number of name-value pairs
235
* @return Headers instance
236
*/
237
fun headersOf(vararg pairs: Pair<String, String>): Headers
238
```
239
240
### Header Value Parsing
241
242
Utilities for parsing complex header values with parameters.
243
244
```kotlin { .api }
245
/**
246
* Header value with parameters (base class for complex headers)
247
*/
248
abstract class HeaderValueWithParameters(
249
protected val content: String,
250
val parameters: List<HeaderValueParam>
251
) {
252
/**
253
* Get parameter value by name
254
* @param name Parameter name
255
* @return Parameter value or null
256
*/
257
fun parameter(name: String): String?
258
}
259
260
/**
261
* Header value parameter
262
*/
263
data class HeaderValueParam(
264
val name: String,
265
val value: String,
266
val escapeValue: Boolean = false
267
)
268
269
/**
270
* Simple header value with quality factor
271
*/
272
data class HeaderValue(
273
val value: String,
274
val params: List<HeaderValueParam> = emptyList()
275
) {
276
val quality: Double
277
}
278
279
/**
280
* Parse header value into structured format
281
* @param value Raw header value
282
* @return List of parsed HeaderValue instances
283
*/
284
fun parseHeaderValue(value: String): List<HeaderValue>
285
286
/**
287
* Parse header value with semicolon handling
288
* @param value Raw header value
289
* @param preserveSemicolons Whether to preserve semicolons
290
* @return List of parsed HeaderValue instances
291
*/
292
fun parseHeaderValue(value: String, preserveSemicolons: Boolean): List<HeaderValue>
293
294
/**
295
* Parse and sort header values by quality factor
296
* @param value Raw header value
297
* @return Sorted list of HeaderValue instances
298
*/
299
fun parseAndSortHeader(value: String): List<HeaderValue>
300
301
/**
302
* Parse and sort Content-Type header values
303
* @param value Raw Content-Type header value
304
* @return Sorted list of HeaderValue instances
305
*/
306
fun parseAndSortContentTypeHeader(value: String): List<HeaderValue>
307
```
308
309
### Header Value Utilities
310
311
Utilities for working with header values and parameters.
312
313
```kotlin { .api }
314
/**
315
* Escape header value if needed
316
* @param value Value to escape
317
* @return Escaped value
318
*/
319
fun escapeIfNeeded(value: String): String
320
321
/**
322
* Quote header value
323
* @param value Value to quote
324
* @return Quoted value
325
*/
326
fun quote(value: String): String
327
328
/**
329
* Append header value with parameters to builder
330
* @param builder String values builder
331
* @param name Header name
332
* @param value Header value with parameters
333
*/
334
fun StringValuesBuilder.append(name: String, value: HeaderValueWithParameters)
335
```
336
337
**Usage Examples:**
338
339
```kotlin
340
import io.ktor.http.*
341
342
// Create headers using builder
343
val headers = headers {
344
append(HttpHeaders.Accept, "application/json")
345
append(HttpHeaders.Accept, "text/html")
346
set(HttpHeaders.UserAgent, "MyApp/1.0")
347
set(HttpHeaders.ContentType, "application/json; charset=utf-8")
348
}
349
350
// Create headers from pairs
351
val simpleHeaders = headersOf(
352
HttpHeaders.Authorization to "Bearer token123",
353
HttpHeaders.ContentType to "application/json"
354
)
355
356
// Access header values
357
val accept = headers[HttpHeaders.Accept] // First value
358
val allAccept = headers.getAll(HttpHeaders.Accept) // All values
359
val hasAuth = headers.contains(HttpHeaders.Authorization)
360
361
// Validate headers
362
try {
363
HttpHeaders.checkHeaderName("Custom-Header")
364
HttpHeaders.checkHeaderValue("some-value")
365
} catch (e: IllegalHeaderNameException) {
366
println("Invalid header name: ${e.headerName}")
367
}
368
369
// Parse complex header values
370
val acceptHeader = "application/json;q=0.9,text/html;q=0.8"
371
val parsed = parseAndSortHeader(acceptHeader)
372
for (value in parsed) {
373
println("${value.value} with quality ${value.quality}")
374
}
375
376
// Check unsafe headers
377
val isUnsafe = HttpHeaders.isUnsafe("Cookie") // true in browser context
378
```
379
380
### Header Implementations
381
382
Concrete implementations of the Headers interface.
383
384
```kotlin { .api }
385
/**
386
* Default implementation of Headers
387
*/
388
class HeadersImpl(values: Map<String, List<String>> = emptyMap()) : Headers, StringValuesImpl(values)
389
390
/**
391
* Single header implementation (optimized for one header)
392
*/
393
class HeadersSingleImpl(name: String, values: List<String>) : Headers, StringValuesSingleImpl(name, values)
394
```
395
396
### Exception Types
397
398
Exceptions thrown by header validation and processing.
399
400
```kotlin { .api }
401
/**
402
* Exception thrown for invalid header names
403
*/
404
class IllegalHeaderNameException(val headerName: String, val position: Int) : IllegalArgumentException()
405
406
/**
407
* Exception thrown for invalid header values
408
*/
409
class IllegalHeaderValueException(val headerValue: String, val position: Int) : IllegalArgumentException()
410
411
/**
412
* Exception thrown when attempting to use unsafe headers
413
*/
414
class UnsafeHeaderException(headerName: String) : IllegalArgumentException()
415
```