Url Parsing in Racket

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

#lang racket

(require net/url)

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

  ; Parse the URL and ensure there are no errors.
  (define u (string->url s))

  ; Accessing the scheme is straightforward.
  (displayln (url-scheme u))

  ; User contains all authentication info; we can access
  ; username and password separately.
  (displayln (url-user u))
  (displayln (url-user u))
  (displayln (url-password u))

  ; The host contains both the hostname and the port,
  ; if present. We can access them separately.
  (displayln (url-host u))
  (displayln (url-host u))
  (displayln (url-port u))

  ; Here we extract the path and the fragment after
  ; the #.
  (displayln (url-path u))
  (displayln (url-fragment u))

  ; To get query params in a string of k=v format,
  ; use url-query. You can also parse query params
  ; into a list of key-value pairs.
  (displayln (url-query u))
  (define m (form-urlencoded->alist (url-query u)))
  (displayln m)
  (displayln (cdar m)))

(main)

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

$ racket url-parsing.rkt
postgres
user:pass
user
pass
host.com
host.com
5432
(path)
f
((k . v))
((k . v))
v

In this Racket version:

  1. We use the net/url library for URL parsing.

  2. The string->url function is used to parse the URL string into a URL object.

  3. We access different parts of the URL using functions like url-scheme, url-user, url-password, etc.

  4. For query parameters, we use form-urlencoded->alist to convert the query string into an association list.

  5. Racket doesn’t have a direct equivalent to Go’s net.SplitHostPort, so we just display the host and port separately.

  6. Error handling is implicit in Racket, so we don’t need explicit error checking as in the Go version.

This example demonstrates how to parse and extract information from URLs in Racket, covering the same concepts as the original Go example.