Url Parsing in GDScript
extends Node
func _ready():
# We'll parse this example URL, which includes a
# scheme, authentication info, host, port, path,
# query params, and query fragment.
var s = "postgres://user:pass@host.com:5432/path?k=v#f"
# Parse the URL and ensure there are no errors.
var url = URL.parse_url(s)
if url == null:
push_error("Failed to parse URL")
return
# Accessing the scheme is straightforward.
print(url.scheme)
# User contains all authentication info; we need to parse it manually.
var user_info = url.user.split(":")
print(url.user)
print(user_info[0]) # username
print(user_info[1] if user_info.size() > 1 else "") # password
# The Host contains both the hostname and the port,
# if present. We need to split them manually.
print(url.host)
var host_parts = url.host.split(":")
var host = host_parts[0]
var port = host_parts[1] if host_parts.size() > 1 else ""
print(host)
print(port)
# Here we extract the path and the fragment after the #.
print(url.path)
print(url.fragment)
# To get query params in a string of k=v format,
# use the query string. You can also parse query params
# into a dictionary.
print(url.query)
var query_params = parse_query_string(url.query)
print(query_params)
print(query_params.get("k", ""))
func parse_query_string(query: String) -> Dictionary:
var result = {}
var pairs = query.split("&")
for pair in pairs:
var kv = pair.split("=")
if kv.size() == 2:
result[kv[0]] = kv[1]
return result
This script demonstrates URL parsing in GDScript. Here’s a breakdown of the changes and explanations:
We use GDScript’s
extends Node
to create a script that can be attached to a Node in the Godot engine.The
_ready()
function is used as the entry point, similar tomain()
in other languages.GDScript doesn’t have a built-in URL parsing library as comprehensive as Go’s, so we use the
URL.parse_url()
method, which provides basic URL parsing.Error handling is done using
if url == null
andpush_error()
instead of Go’s panic.User info, host, and port parsing are done manually since GDScript’s URL parsing doesn’t separate these components.
Query string parsing is implemented in a separate function
parse_query_string()
since GDScript doesn’t provide this functionality out of the box.We use GDScript’s
print()
function instead offmt.Println()
.Dictionary access in GDScript uses
.get()
with a default value instead of indexing.
To run this script in Godot:
- Create a new Godot project and attach this script to a Node in your scene.
- Run the scene, and you’ll see the output in the Godot output panel.
This script provides similar functionality to the Go example, parsing and extracting various components of a URL. However, due to the differences between Go and GDScript, some operations (like user info and query string parsing) require manual implementation.