Url Parsing in Groovy

Here’s the translation of the Go URL parsing example to Groovy:

Our URL parsing program demonstrates how to parse and extract different components from a URL. Here’s the full source code:

import java.net.URI

def s = "postgres://user:pass@host.com:5432/path?k=v#f"

// Parse the URL and ensure there are no errors.
def u = new URI(s)

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

// UserInfo contains all authentication info; we need to parse it manually.
def userInfo = u.userInfo
println userInfo
if (userInfo) {
    def (username, password) = userInfo.split(':')
    println username
    println password
}

// The host contains both the hostname and the port, if present.
println u.host
def host = u.host
def port = u.port
println host
println 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.
println u.query

// You can also parse query params into a map.
def queryParams = u.query.split('&').collectEntries { param ->
    def (key, value) = param.split('=')
    [(key): value]
}
println queryParams
println queryParams['k']

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

$ groovy url-parsing.groovy
postgres
user:pass
user
pass
host.com
5432
/path
f
k=v
[k:v]
v

This example demonstrates how to use Groovy’s URI class to parse URLs. The URI class provides methods to access different components of a URL such as scheme, user info, host, port, path, query, and fragment.

Note that unlike Go’s url.Parse function, Groovy’s URI class doesn’t separate the host and port automatically, so we need to handle that manually if needed. Also, for parsing query parameters, we’ve used a Groovy-specific approach to split the query string and convert it into a map.

The program structure and explanations have been maintained as closely as possible to the original, while adapting to Groovy’s syntax and standard library.