Url Parsing in Scala
Here’s the translation of the Go URL parsing example to Scala, formatted in Markdown suitable for Hugo:
import java.net.URI
import scala.jdk.CollectionConverters._
object URLParsing {
def main(args: Array[String]): Unit = {
// 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 uri = URI.create(s)
// Accessing the scheme is straightforward.
println(uri.getScheme)
// UserInfo contains all authentication info; we need to split it
// to get individual username and password.
val userInfo = uri.getUserInfo
println(userInfo)
val Array(username, password) = userInfo.split(":")
println(username)
println(password)
// The Host contains both the hostname and the port,
// if present. We need to split them manually.
println(uri.getHost + ":" + uri.getPort)
println(uri.getHost)
println(uri.getPort)
// Here we extract the path and the fragment after
// the #.
println(uri.getPath)
println(uri.getFragment)
// To get query params in a string of k=v format,
// use getRawQuery. You can also parse query params
// into a map.
println(uri.getRawQuery)
val queryParams = uri.getQuery.split("&")
.map(_.split("="))
.map(arr => arr(0) -> arr(1))
.toMap
println(queryParams)
println(queryParams("k"))
}
}
This Scala program demonstrates URL parsing using the java.net.URI
class. Here’s a breakdown of what it does:
We start by importing necessary classes and methods.
We define our example URL string, which includes various components like scheme, authentication info, host, port, path, query parameters, and fragment.
We create a
URI
object from our string usingURI.create(s)
.We extract various components of the URL:
- Scheme using
getScheme()
- User info using
getUserInfo()
, which we then split to get username and password - Host and port using
getHost()
andgetPort()
- Path using
getPath()
- Fragment using
getFragment()
- Query string using
getRawQuery()
- Scheme using
For query parameters, we split the query string and convert it into a Map for easy access.
To run this Scala program:
$ scala URLParsing.scala
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
Map(k -> v)
v
This output shows all the different pieces that we extracted from the URL.
In Scala, we use the java.net.URI
class which provides similar functionality to Go’s url.URL
. However, some operations (like splitting the user info and parsing query parameters) need to be done manually in Scala.