CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor

A multiplatform asynchronous framework for creating microservices, web applications, and HTTP clients written in Kotlin from the ground up

Pending
Overview
Eval results
Files

http-utilities.mddocs/

HTTP Utilities

Core HTTP types, utilities, and extensions for working with HTTP protocols in Ktor.

Capabilities

HTTP Methods

Standard HTTP methods enumeration with value and semantic information.

/**
 * HTTP methods enumeration
 */
enum class HttpMethod(val value: String) {
    Get("GET"),
    Post("POST"),
    Put("PUT"),
    Delete("DELETE"),
    Head("HEAD"),
    Options("OPTIONS"),
    Patch("PATCH");
    
    companion object {
        /**
         * Parse HTTP method from string
         */
        fun parse(method: String): HttpMethod
        
        /**
         * All default HTTP methods
         */
        val DefaultMethods: List<HttpMethod>
    }
}

Usage Examples:

import io.ktor.http.*

// Using HTTP methods
val method = HttpMethod.Get
println(method.value) // "GET"

// Parsing from string
val parsed = HttpMethod.parse("POST") // HttpMethod.Post

// Custom methods
val customMethod = HttpMethod("CUSTOM")

HTTP Status Codes

Comprehensive HTTP status code definitions with descriptions.

/**
 * HTTP status code with value and description
 */
data class HttpStatusCode(val value: Int, val description: String) {
    companion object {
        // 1xx Informational
        val Continue = HttpStatusCode(100, "Continue")
        val SwitchingProtocols = HttpStatusCode(101, "Switching Protocols")
        val Processing = HttpStatusCode(102, "Processing")
        
        // 2xx Success
        val OK = HttpStatusCode(200, "OK")
        val Created = HttpStatusCode(201, "Created")
        val Accepted = HttpStatusCode(202, "Accepted")
        val NonAuthoritativeInformation = HttpStatusCode(203, "Non-Authoritative Information")
        val NoContent = HttpStatusCode(204, "No Content")
        val ResetContent = HttpStatusCode(205, "Reset Content")
        val PartialContent = HttpStatusCode(206, "Partial Content")
        
        // 3xx Redirection
        val MultipleChoices = HttpStatusCode(300, "Multiple Choices")
        val MovedPermanently = HttpStatusCode(301, "Moved Permanently")
        val Found = HttpStatusCode(302, "Found")
        val SeeOther = HttpStatusCode(303, "See Other")
        val NotModified = HttpStatusCode(304, "Not Modified")
        val UseProxy = HttpStatusCode(305, "Use Proxy")
        val TemporaryRedirect = HttpStatusCode(307, "Temporary Redirect")
        val PermanentRedirect = HttpStatusCode(308, "Permanent Redirect")
        
        // 4xx Client Error
        val BadRequest = HttpStatusCode(400, "Bad Request")
        val Unauthorized = HttpStatusCode(401, "Unauthorized")
        val PaymentRequired = HttpStatusCode(402, "Payment Required")
        val Forbidden = HttpStatusCode(403, "Forbidden")
        val NotFound = HttpStatusCode(404, "Not Found")
        val MethodNotAllowed = HttpStatusCode(405, "Method Not Allowed")
        val NotAcceptable = HttpStatusCode(406, "Not Acceptable")
        val RequestTimeout = HttpStatusCode(408, "Request Timeout")
        val Conflict = HttpStatusCode(409, "Conflict")
        val Gone = HttpStatusCode(410, "Gone")
        val UnprocessableEntity = HttpStatusCode(422, "Unprocessable Entity")
        val TooManyRequests = HttpStatusCode(429, "Too Many Requests")
        
        // 5xx Server Error
        val InternalServerError = HttpStatusCode(500, "Internal Server Error")
        val NotImplemented = HttpStatusCode(501, "Not Implemented")
        val BadGateway = HttpStatusCode(502, "Bad Gateway")
        val ServiceUnavailable = HttpStatusCode(503, "Service Unavailable")
        val GatewayTimeout = HttpStatusCode(504, "Gateway Timeout")
        val VersionNotSupported = HttpStatusCode(505, "HTTP Version Not Supported")
        
        /**
         * Find status code by value
         */
        fun fromValue(value: Int): HttpStatusCode
        
        /**
         * All status codes by category
         */
        val allStatusCodes: List<HttpStatusCode>
    }
    
    /**
     * Check if status code is successful (2xx)
     */
    val isSuccess: Boolean get() = value in 200..299
    
    /**
     * Check if status code is informational (1xx)
     */
    val isInformational: Boolean get() = value in 100..199
    
    /**
     * Check if status code is redirection (3xx)
     */
    val isRedirection: Boolean get() = value in 300..399
    
    /**
     * Check if status code is client error (4xx)
     */
    val isClientError: Boolean get() = value in 400..499
    
    /**
     * Check if status code is server error (5xx)
     */
    val isServerError: Boolean get() = value in 500..599
}

Headers Interface

HTTP headers container with case-insensitive access and manipulation.

/**
 * HTTP headers interface
 */
interface Headers : StringValues {
    companion object {
        /**
         * Empty headers instance
         */
        val Empty: Headers
        
        /**
         * Build headers from key-value pairs
         */
        fun build(builder: HeadersBuilder.() -> Unit = {}): Headers
    }
}

/**
 * Mutable headers builder
 */
class HeadersBuilder : StringValuesBuilder {
    /**
     * Append header value
     */
    fun append(name: String, value: String)
    
    /**
     * Set header value (replaces existing)
     */
    operator fun set(name: String, value: String)
    
    /**
     * Remove header
     */
    fun remove(name: String): Boolean
    
    /**
     * Build immutable headers
     */
    fun build(): Headers
}

/**
 * String values interface for headers and parameters
 */
interface StringValues {
    /**
     * Get first value for name
     */
    operator fun get(name: String): String?
    
    /**
     * Get all values for name
     */
    fun getAll(name: String): List<String>?
    
    /**
     * Check if name exists
     */
    operator fun contains(name: String): Boolean
    
    /**
     * Check if empty
     */
    fun isEmpty(): Boolean
    
    /**
     * Get all names
     */
    fun names(): Set<String>
    
    /**
     * Get all entries
     */
    fun entries(): Set<Map.Entry<String, List<String>>>
    
    /**
     * Iterate over entries
     */
    fun forEach(action: (String, List<String>) -> Unit)
}

Usage Examples:

import io.ktor.http.*

// Build headers
val headers = Headers.build {
    append("Content-Type", "application/json")
    append("Accept", "application/json")
    append("Authorization", "Bearer token123")
    set("User-Agent", "Ktor Client")
}

// Access headers
val contentType = headers["Content-Type"] // "application/json"
val acceptHeaders = headers.getAll("Accept") // ["application/json"]
val hasAuth = "Authorization" in headers // true

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

Content Types

MIME type representations and content type handling.

/**
 * Content type representation
 */
data class ContentType(
    val contentType: String,
    val contentSubtype: String,
    val parameters: List<HeaderValueParam> = emptyList()
) {
    companion object {
        // Text types
        val Text = ContentType("text", "*")
        val Text.Plain = ContentType("text", "plain")
        val Text.CSS = ContentType("text", "css")
        val Text.CSV = ContentType("text", "csv")
        val Text.Html = ContentType("text", "html")
        val Text.JavaScript = ContentType("text", "javascript")
        val Text.VCard = ContentType("text", "vcard")
        val Text.Xml = ContentType("text", "xml")
        
        // Application types
        val Application = ContentType("application", "*")
        val Application.Atom = ContentType("application", "atom+xml")
        val Application.Json = ContentType("application", "json")
        val Application.JavaScript = ContentType("application", "javascript")
        val Application.OctetStream = ContentType("application", "octet-stream")
        val Application.FontWoff = ContentType("application", "font-woff")
        val Application.Rss = ContentType("application", "rss+xml")
        val Application.Xml = ContentType("application", "xml")
        val Application.Zip = ContentType("application", "zip")
        val Application.GZip = ContentType("application", "gzip")
        val Application.FormUrlEncoded = ContentType("application", "x-www-form-urlencoded")
        val Application.Pdf = ContentType("application", "pdf")
        
        // Multipart types
        val MultiPart = ContentType("multipart", "*")
        val MultiPart.Mixed = ContentType("multipart", "mixed")
        val MultiPart.Alternative = ContentType("multipart", "alternative")
        val MultiPart.Related = ContentType("multipart", "related")
        val MultiPart.FormData = ContentType("multipart", "form-data")
        val MultiPart.Signed = ContentType("multipart", "signed")
        val MultiPart.Encrypted = ContentType("multipart", "encrypted")
        val MultiPart.ByteRanges = ContentType("multipart", "byteranges")
        
        // Image types
        val Image = ContentType("image", "*")
        val Image.JPEG = ContentType("image", "jpeg")
        val Image.PNG = ContentType("image", "png")
        val Image.GIF = ContentType("image", "gif")
        val Image.SVG = ContentType("image", "svg+xml")
        
        // Audio types
        val Audio = ContentType("audio", "*")
        val Audio.MP4 = ContentType("audio", "mp4")
        val Audio.MPEG = ContentType("audio", "mpeg")
        val Audio.OGG = ContentType("audio", "ogg")
        
        // Video types
        val Video = ContentType("video", "*")
        val Video.MPEG = ContentType("video", "mpeg")
        val Video.MP4 = ContentType("video", "mp4")
        val Video.OGG = ContentType("video", "ogg")
        val Video.QuickTime = ContentType("video", "quicktime")
        
        /**
         * Parse content type from string
         */
        fun parse(value: String): ContentType
    }
    
    /**
     * Content type with charset parameter
     */
    fun withCharset(charset: Charset): ContentType
    
    /**
     * Content type with parameter
     */
    fun withParameter(name: String, value: String): ContentType
    
    /**
     * Match against another content type
     */
    fun match(pattern: ContentType): Boolean
    
    /**
     * String representation
     */
    override fun toString(): String
}

URL Building

URL construction and manipulation utilities.

/**
 * URL builder for constructing URLs programmatically
 */
class URLBuilder(
    var protocol: URLProtocol = URLProtocol.HTTP,
    var host: String = "localhost",
    var port: Int = DEFAULT_PORT,
    var user: String? = null,
    var password: String? = null,
    var pathSegments: MutableList<String> = mutableListOf(),
    var parameters: ParametersBuilder = ParametersBuilder(),
    var fragment: String = "",
    var trailingQuery: Boolean = false
) {
    /**
     * Build URL string
     */
    fun buildString(): String
    
    /**
     * Build Url object
     */
    fun build(): Url
    
    /**
     * Clone this builder
     */
    fun clone(): URLBuilder
}

/**
 * URL protocol enumeration
 */
enum class URLProtocol(val name: String, val defaultPort: Int) {
    HTTP("http", 80),
    HTTPS("https", 443),
    WS("ws", 80),
    WSS("wss", 443),
    FILE("file", 0),
    SOCKS("socks", 1080);
    
    companion object {
        /**
         * Create protocol from name
         */
        fun createOrDefault(name: String): URLProtocol
    }
}

/**
 * Immutable URL representation
 */
data class Url(
    val protocol: URLProtocol,
    val host: String,
    val port: Int,
    val user: String?,
    val password: String?,
    val pathSegments: List<String>,
    val parameters: Parameters,
    val fragment: String,
    val trailingQuery: Boolean
) {
    companion object {
        /**
         * Parse URL from string
         */
        fun parse(urlString: String): Url
    }
    
    /**
     * Convert to string
     */
    override fun toString(): String
}

Usage Examples:

import io.ktor.http.*

// Build URL programmatically
val url = URLBuilder().apply {
    protocol = URLProtocol.HTTPS
    host = "api.example.com"
    port = 443
    pathSegments.addAll(listOf("v1", "users"))
    parameters.append("page", "1")
    parameters.append("limit", "10")
}.buildString()
// Result: "https://api.example.com/v1/users?page=1&limit=10"

// Parse existing URL
val parsed = Url.parse("https://example.com:8080/path?query=value#section")
println(parsed.host) // "example.com"
println(parsed.port) // 8080
println(parsed.pathSegments) // ["path"]

Parameters Interface

URL parameters and form data handling.

/**
 * Parameters interface for URL query parameters and form data
 */
interface Parameters : StringValues {
    companion object {
        /**
         * Empty parameters instance
         */
        val Empty: Parameters
        
        /**
         * Build parameters from key-value pairs
         */
        fun build(builder: ParametersBuilder.() -> Unit = {}): Parameters
    }
}

/**
 * Mutable parameters builder
 */
class ParametersBuilder : StringValuesBuilder {
    /**
     * Append parameter value
     */
    fun append(name: String, value: String)
    
    /**
     * Set parameter value (replaces existing)
     */
    operator fun set(name: String, value: String)
    
    /**
     * Remove parameter
     */
    fun remove(name: String): Boolean
    
    /**
     * Append all values from another Parameters
     */
    fun appendAll(other: Parameters)
    
    /**
     * Build immutable parameters
     */
    fun build(): Parameters
}

HTTP Authentication

HTTP authentication utilities and challenges.

/**
 * HTTP authentication challenge
 */
sealed class HttpAuthHeader {
    /**
     * Basic authentication challenge
     */
    data class Single(val authScheme: String, val parameter: String) : HttpAuthHeader()
    
    /**
     * Parameterized authentication challenge
     */
    data class Parameterized(
        val authScheme: String,
        val parameters: List<HeaderValueParam>
    ) : HttpAuthHeader()
    
    companion object {
        /**
         * Parse authentication header
         */
        fun parse(headerValue: String): HttpAuthHeader?
    }
}

/**
 * Header value parameter
 */
data class HeaderValueParam(val name: String, val value: String) {
    /**
     * Parameter with escaped value
     */
    val escapeIfNeeded: String
}

Install with Tessl CLI

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

docs

client-management.md

engine-system.md

form-data.md

http-utilities.md

index.md

plugin-system.md

request-operations.md

response-handling.md

routing-system.md

server-framework.md

tile.json