or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdcontent-processing.mdcontent-types.mdcookies.mddate-utilities.mdheader-parsing.mdheaders.mdhttp-message-extensions.mdhttp-methods-status.mdindex.mdmultipart.mdparameters.mdurl-encoding.mdurl-handling.md
tile.json

headers.mddocs/

Headers Management

Type-safe HTTP header handling with constants for all standard headers, validation, case-insensitive access, and builder patterns for constructing header collections.

Capabilities

HTTP Header Constants

Object containing string constants for all standard HTTP headers, WebSocket headers, CORS headers, and common X-headers.

/**
 * HTTP header name constants for type-safe header access
 */
object HttpHeaders {
    // Standard Headers
    const val Accept: String
    const val AcceptCharset: String
    const val AcceptEncoding: String
    const val AcceptLanguage: String
    const val AcceptRanges: String
    const val Age: String
    const val Allow: String
    const val ALPN: String
    const val AuthenticationInfo: String
    const val Authorization: String
    const val CacheControl: String
    const val Connection: String
    const val ContentDisposition: String
    const val ContentEncoding: String
    const val ContentLanguage: String
    const val ContentLength: String
    const val ContentLocation: String
    const val ContentRange: String
    const val ContentType: String
    const val Cookie: String
    const val Date: String
    const val ETag: String
    const val Expect: String
    const val Expires: String
    const val From: String
    const val Forwarded: String
    const val Host: String
    const val IfMatch: String
    const val IfModifiedSince: String
    const val IfNoneMatch: String
    const val IfRange: String
    const val IfUnmodifiedSince: String
    const val LastModified: String
    const val Location: String
    const val Link: String
    const val MaxForwards: String
    const val Origin: String
    const val Pragma: String
    const val Range: String
    const val Referrer: String
    const val RetryAfter: String
    const val Server: String
    const val SetCookie: String
    const val TransferEncoding: String
    const val Upgrade: String
    const val UserAgent: String
    const val Vary: String
    const val Via: String
    const val Warning: String
    const val WWWAuthenticate: String
    
    // WebSocket Headers
    const val SecWebSocketAccept: String
    const val SecWebSocketExtensions: String
    const val SecWebSocketKey: String
    const val SecWebSocketProtocol: String  
    const val SecWebSocketVersion: String
    
    // CORS Headers
    const val AccessControlAllowOrigin: String
    const val AccessControlAllowMethods: String
    const val AccessControlAllowCredentials: String
    const val AccessControlAllowHeaders: String
    const val AccessControlRequestMethod: String
    const val AccessControlRequestHeaders: String
    const val AccessControlExposeHeaders: String
    const val AccessControlMaxAge: String
    
    // X-Headers (Unofficial)
    const val XHttpMethodOverride: String
    const val XForwardedHost: String
    const val XForwardedServer: String
    const val XForwardedProto: String
    const val XForwardedFor: String
    const val XForwardedPort: String
    const val XRequestId: String
    const val XCorrelationId: String
    const val XTotalCount: String
    
    /** List of headers considered unsafe for certain contexts */
    val UnsafeHeadersList: List<String>
    
    /**
     * Check if a header is considered unsafe
     * @param header the header name to check
     * @return true if header is unsafe
     */
    fun isUnsafe(header: String): Boolean
    
    /**
     * Validate header name format
     * @param name the header name to validate
     * @throws IllegalHeaderNameException if name is invalid
     */
    fun checkHeaderName(name: String)
    
    /**
     * Validate header value format
     * @param value the header value to validate
     * @throws IllegalHeaderValueException if value is invalid
     */
    fun checkHeaderValue(value: String)
}

Headers Interface

Case-insensitive header collection interface extending StringValues.

/**
 * Case-insensitive HTTP headers collection
 */
interface Headers : StringValues {
    companion object {
        /** Empty headers instance */
        val Empty: Headers
        
        /**
         * Build headers using DSL
         * @param builder the headers builder function
         * @return Headers instance
         */
        fun build(builder: HeadersBuilder.() -> Unit): Headers
    }
}

/**
 * Builder for constructing Headers instances
 */
class HeadersBuilder(size: Int = 8) : StringValuesBuilder {
    /**
     * Build the final Headers instance
     * @return immutable Headers
     */
    fun build(): Headers
}

Headers Factory Functions

Convenient functions for creating Headers instances from various inputs.

/**
 * Create empty headers
 * @return empty Headers instance
 */
fun headersOf(): Headers

/**
 * Create headers with single name-value pair
 * @param name header name
 * @param value header value
 * @return Headers instance
 */
fun headersOf(name: String, value: String): Headers

/**
 * Create headers with single name and multiple values
 * @param name header name
 * @param values list of header values
 * @return Headers instance
 */
fun headersOf(name: String, values: List<String>): Headers

/**
 * Create headers from pairs of names to value lists
 * @param pairs vararg pairs of header name to value list
 * @return Headers instance
 */
fun headersOf(vararg pairs: Pair<String, List<String>>): Headers

/**
 * Create headers using builder DSL
 * @param builder the headers builder function
 * @return Headers instance
 */
fun headers(builder: HeadersBuilder.() -> Unit): Headers

Header Validation Exceptions

Exceptions thrown when header names or values are invalid.

/**
 * Exception thrown when trying to use an unsafe header
 * @param header the unsafe header name
 */
class UnsafeHeaderException(header: String) : IllegalArgumentException

/**
 * Exception thrown for invalid header names
 * @param headerName the invalid header name
 * @param position position of the invalid character
 */
class IllegalHeaderNameException(
    headerName: String, 
    position: Int
) : IllegalArgumentException

/**
 * Exception thrown for invalid header values
 * @param headerValue the invalid header value
 * @param position position of the invalid character
 */
class IllegalHeaderValueException(
    headerValue: String, 
    position: Int
) : IllegalArgumentException

Usage Examples:

import io.ktor.http.*

// Create headers using factory functions
val emptyHeaders = headersOf()

val singleHeader = headersOf(
    HttpHeaders.ContentType, 
    "application/json"
)

val multipleValues = headersOf(
    HttpHeaders.Accept, 
    listOf("application/json", "text/plain")
)

// Create headers using DSL
val headers = headers {
    append(HttpHeaders.Authorization, "Bearer token123")
    append(HttpHeaders.ContentType, "application/json")
    append(HttpHeaders.Accept, "application/json")
    append(HttpHeaders.UserAgent, "MyApp/1.0")
}

// Access header values (case-insensitive)
val contentType = headers[HttpHeaders.ContentType]
val authorization = headers["authorization"] // case-insensitive
val acceptValues = headers.getAll(HttpHeaders.Accept)

// Check if header exists
val hasAuth = headers.contains(HttpHeaders.Authorization)
val hasContentType = HttpHeaders.ContentType in headers

// Iterate through headers
headers.entries().forEach { (name, values) ->
    println("$name: ${values.joinToString(", ")}")
}

// Header validation
try {
    HttpHeaders.checkHeaderName("Valid-Header-Name")
    HttpHeaders.checkHeaderValue("valid value")
} catch (e: IllegalHeaderNameException) {
    println("Invalid header name: ${e.message}")
} catch (e: IllegalHeaderValueException) {
    println("Invalid header value: ${e.message}")
}

// Check for unsafe headers
if (HttpHeaders.isUnsafe("Connection")) {
    println("Connection header is considered unsafe")
}

// Build headers incrementally
val builder = HeadersBuilder()
builder.append(HttpHeaders.Host, "example.com")
builder.append(HttpHeaders.ContentLength, "1234")
val builtHeaders = builder.build()

Types

/**
 * Implementation of Headers interface
 */
class HeadersImpl(values: Map<String, List<String>>) : Headers

/**
 * Single header implementation for optimization
 */
class HeadersSingleImpl(
    name: String, 
    values: List<String>
) : Headers