Url Parsing in Kotlin

Here’s the translation of the Go URL parsing example to Kotlin, formatted in Markdown suitable for Hugo:

import java.net.URI
import java.net.URLDecoder

fun main() {
    // We'll parse this example URL, which includes a
    // scheme, authentication info, host, port, path,
    // query params, and query fragment.
    val s = "postgres://user:pass@host.com:5432/path?k=v#f"

    // Parse the URL and ensure there are no errors.
    val u = try {
        URI(s)
    } catch (e: Exception) {
        println("Failed to parse URL: ${e.message}")
        return
    }

    // Accessing the scheme is straightforward.
    println(u.scheme)

    // User contains all authentication info; we need to parse it manually.
    val userInfo = u.userInfo?.split(':')
    println(u.userInfo)
    println(userInfo?.getOrNull(0))
    println(userInfo?.getOrNull(1))

    // The Host contains both the hostname and the port,
    // if present. We can access them separately.
    println(u.host)
    println(u.port)

    // Here we extract the path and the fragment after the #.
    println(u.path)
    println(u.fragment)

    // To get query params in a string of k=v format,
    // use query. You can also parse query params
    // into a map.
    println(u.query)
    val queryParams = u.query?.split('&')?.associate {
        val (key, value) = it.split('=')
        URLDecoder.decode(key, "UTF-8") to URLDecoder.decode(value, "UTF-8")
    }
    println(queryParams)
    println(queryParams?.get("k"))
}

Running our URL parsing program shows all the different pieces that we extracted.

$ kotlin url-parsing.kt
postgres
user:pass
user
pass
host.com
5432
/path
f
k=v
{k=v}
v

In this Kotlin version:

  1. We use the java.net.URI class to parse the URL, which is similar to Go’s url.Parse().

  2. The URI class doesn’t provide direct access to username and password separately, so we split the userInfo string manually.

  3. Kotlin doesn’t have a direct equivalent to Go’s net.SplitHostPort(), but URI provides separate host and port properties.

  4. Query parameter parsing is done manually using Kotlin’s collection functions, as there’s no direct equivalent to Go’s url.ParseQuery().

  5. Error handling is done using a try-catch block instead of Go’s error return.

  6. We use Kotlin’s null safety features (like ?. and getOrNull()) to handle potentially missing parts of the URL.

This example demonstrates how to parse and extract information from URLs in Kotlin, covering all the main components of a URL structure.