CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-http-js

JavaScript/WebAssembly implementation of Ktor's HTTP core library providing HTTP utilities, URL building, request/response handling, and HTTP method definitions for multiplatform Kotlin applications targeting JavaScript environments

Pending
Overview
Eval results
Files

headers.mddocs/

Headers Management

Comprehensive header management with immutable collections, builder patterns, and standard HTTP header constants.

Capabilities

Headers Interface

Immutable collection of HTTP headers extending StringValues for key-value access.

/**
 * Immutable collection of HTTP headers
 */
interface Headers : StringValues {
    companion object {
        val Empty: Headers
        
        /**
         * Build headers using a builder function
         * @param builder Function to configure headers
         * @return Immutable Headers instance
         */
        fun build(builder: HeadersBuilder.() -> Unit): Headers
    }
}

Headers Builder

Mutable builder for constructing Headers instances.

/**
 * Mutable builder for HTTP headers
 */
class HeadersBuilder : StringValuesBuilderImpl() {
    /**
     * Append a header value (allows multiple values for same header)
     * @param name Header name
     * @param value Header value
     */
    fun append(name: String, value: String)
    
    /**
     * Set a header value (replaces existing values)
     * @param name Header name  
     * @param value Header value
     */
    fun set(name: String, value: String)
    
    /**
     * Remove all values for a header
     * @param name Header name
     */
    fun remove(name: String)
    
    /**
     * Build immutable Headers instance
     * @return Headers containing all added headers
     */
    fun build(): Headers
}

Standard HTTP Headers

Constants for all standard HTTP header names with validation utilities.

/**
 * Standard HTTP header names
 */
object HttpHeaders {
    // Request headers
    val Accept: String
    val AcceptCharset: String
    val AcceptEncoding: String
    val AcceptLanguage: String
    val Authorization: String
    val CacheControl: String  
    val Connection: String
    val Cookie: String
    val ContentLength: String
    val ContentType: String
    val Date: String
    val Expect: String
    val From: String
    val Host: String
    val IfMatch: String
    val IfModifiedSince: String
    val IfNoneMatch: String
    val IfRange: String
    val IfUnmodifiedSince: String
    val MaxForwards: String
    val Origin: String
    val Pragma: String
    val ProxyAuthorization: String
    val Range: String
    val Referrer: String
    val TE: String
    val Upgrade: String
    val UserAgent: String
    val Via: String
    val Warning: String
    
    // Response headers
    val AcceptRanges: String
    val Age: String
    val Allow: String
    val ContentDisposition: String
    val ContentEncoding: String
    val ContentLanguage: String
    val ContentLocation: String
    val ContentRange: String
    val ETag: String
    val Expires: String
    val LastModified: String
    val Link: String
    val Location: String
    val ProxyAuthenticate: String
    val RetryAfter: String
    val Server: String
    val SetCookie: String
    val Trailer: String
    val TransferEncoding: String
    val Vary: String
    val WWWAuthenticate: String
    
    // CORS headers
    val AccessControlAllowCredentials: String
    val AccessControlAllowHeaders: String
    val AccessControlAllowMethods: String
    val AccessControlAllowOrigin: String
    val AccessControlExposeHeaders: String
    val AccessControlMaxAge: String
    val AccessControlRequestHeaders: String
    val AccessControlRequestMethod: String
    
    // Security headers
    val StrictTransportSecurity: String
    val PublicKeyPins: String
    val PublicKeyPinsReportOnly: String
    
    // WebSocket headers
    val SecWebSocketAccept: String
    val SecWebSocketExtensions: String
    val SecWebSocketKey: String
    val SecWebSocketProtocol: String
    val SecWebSocketVersion: String
    
    // Custom headers
    val XCorrelationId: String
    val XForwardedFor: String
    val XForwardedHost: String  
    val XForwardedPort: String
    val XForwardedProto: String
    val XForwardedServer: String
    val XHttpMethodOverride: String
    val XRequestId: String
    val XTotalCount: String
    
    // Additional WebDAV headers
    val DASL: String
    val DAV: String
    val Depth: String
    val Destination: String
    val If: String
    val LockToken: String
    val Overwrite: String
    val Timeout: String
    
    val UnsafeHeaders: Array<String>
    val UnsafeHeadersList: List<String>
    
    /**
     * Validate header name according to HTTP specification
     * @param name Header name to validate
     * @throws IllegalHeaderNameException if invalid
     */
    fun checkHeaderName(name: String)
    
    /**
     * Validate header value according to HTTP specification  
     * @param value Header value to validate
     * @throws IllegalHeaderValueException if invalid
     */
    fun checkHeaderValue(value: String)
    
    /**
     * Check if header name is considered unsafe for browser requests
     * @param name Header name to check
     * @return true if header is unsafe
     */
    fun isUnsafe(name: String): Boolean
}

Header Construction Utilities

Utility functions for creating Headers instances.

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

/**
 * 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
 * @param pairs Variable number of name-value pairs
 * @return Headers instance
 */
fun headersOf(vararg pairs: Pair<String, String>): Headers

Header Value Parsing

Utilities for parsing complex header values with parameters.

/**
 * Header value with parameters (base class for complex headers)
 */
abstract class HeaderValueWithParameters(
    protected val content: String,
    val parameters: List<HeaderValueParam>
) {
    /**
     * Get parameter value by name
     * @param name Parameter name
     * @return Parameter value or null
     */
    fun parameter(name: String): String?
}

/**
 * Header value parameter
 */
data class HeaderValueParam(
    val name: String,
    val value: String,
    val escapeValue: Boolean = false
)

/**
 * Simple header value with quality factor
 */
data class HeaderValue(
    val value: String,
    val params: List<HeaderValueParam> = emptyList()
) {
    val quality: Double
}

/**
 * Parse header value into structured format
 * @param value Raw header value
 * @return List of parsed HeaderValue instances
 */
fun parseHeaderValue(value: String): List<HeaderValue>

/**
 * Parse header value with semicolon handling
 * @param value Raw header value
 * @param preserveSemicolons Whether to preserve semicolons
 * @return List of parsed HeaderValue instances
 */
fun parseHeaderValue(value: String, preserveSemicolons: Boolean): List<HeaderValue>

/**
 * Parse and sort header values by quality factor
 * @param value Raw header value
 * @return Sorted list of HeaderValue instances
 */
fun parseAndSortHeader(value: String): List<HeaderValue>

/**
 * Parse and sort Content-Type header values
 * @param value Raw Content-Type header value
 * @return Sorted list of HeaderValue instances
 */
fun parseAndSortContentTypeHeader(value: String): List<HeaderValue>

Header Value Utilities

Utilities for working with header values and parameters.

/**
 * Escape header value if needed
 * @param value Value to escape
 * @return Escaped value
 */
fun escapeIfNeeded(value: String): String

/**
 * Quote header value
 * @param value Value to quote
 * @return Quoted value
 */
fun quote(value: String): String

/**
 * Append header value with parameters to builder
 * @param builder String values builder
 * @param name Header name
 * @param value Header value with parameters
 */
fun StringValuesBuilder.append(name: String, value: HeaderValueWithParameters)

Usage Examples:

import io.ktor.http.*

// Create headers using builder
val headers = headers {
    append(HttpHeaders.Accept, "application/json")
    append(HttpHeaders.Accept, "text/html")
    set(HttpHeaders.UserAgent, "MyApp/1.0")
    set(HttpHeaders.ContentType, "application/json; charset=utf-8")
}

// Create headers from pairs
val simpleHeaders = headersOf(
    HttpHeaders.Authorization to "Bearer token123",
    HttpHeaders.ContentType to "application/json"
)

// Access header values
val accept = headers[HttpHeaders.Accept] // First value
val allAccept = headers.getAll(HttpHeaders.Accept) // All values
val hasAuth = headers.contains(HttpHeaders.Authorization)

// Validate headers
try {
    HttpHeaders.checkHeaderName("Custom-Header")
    HttpHeaders.checkHeaderValue("some-value")
} catch (e: IllegalHeaderNameException) {
    println("Invalid header name: ${e.headerName}")
}

// Parse complex header values
val acceptHeader = "application/json;q=0.9,text/html;q=0.8"
val parsed = parseAndSortHeader(acceptHeader)
for (value in parsed) {
    println("${value.value} with quality ${value.quality}")
}

// Check unsafe headers
val isUnsafe = HttpHeaders.isUnsafe("Cookie") // true in browser context

Header Implementations

Concrete implementations of the Headers interface.

/**
 * Default implementation of Headers
 */
class HeadersImpl(values: Map<String, List<String>> = emptyMap()) : Headers, StringValuesImpl(values)

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

Exception Types

Exceptions thrown by header validation and processing.

/**
 * Exception thrown for invalid header names
 */
class IllegalHeaderNameException(val headerName: String, val position: Int) : IllegalArgumentException()

/**
 * Exception thrown for invalid header values
 */
class IllegalHeaderValueException(val headerValue: String, val position: Int) : IllegalArgumentException()

/**
 * Exception thrown when attempting to use unsafe headers
 */
class UnsafeHeaderException(headerName: String) : IllegalArgumentException()

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-http-js

docs

authentication.md

content-types.md

content.md

cookies.md

headers.md

http-core.md

index.md

urls.md

tile.json