Make it a script.
日々の作業を、自動化。
Files, text, processes, and scheduled jobs. Turn repeated work into a command.
ファイル、文字列、プロセス、定期実行。繰り返す作業を、ひとつのコマンドに。
Explore the tools →道具を見る →From a quick script to a web service. Bring the language you know to your terminal, with tools for the work ahead.
ちょっとした自動化からWebサービスまで。使い慣れた言語と、必要な道具をターミナルへ。
var app := GD.web.app()
func hello(_req):
return GD.web.json({"message": "Hello!"})
func main():
app.route("GET", "/", hello)
app.listen(8080, "127.0.0.1")!
return 0curl -fsSL https://gd.progsha.com/install.sh | shcurl -fsSL https://gd.progsha.com/install.sh | shInvoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1Files, text, processes, and scheduled jobs. Turn repeated work into a command.
ファイル、文字列、プロセス、定期実行。繰り返す作業を、ひとつのコマンドに。
Explore the tools →道具を見る →Routes, JSON, templates, and middleware. Build an API with the web tools already included.
ルーティング、JSON、テンプレート、ミドルウェア。組み込みの道具でAPIを作る。
Build a web service →Webサービスを作る →Read structured files, query a database, and add packages as your project grows.
構造化ファイルの読み書きから、データベースへのクエリまで。パッケージで広がる開発。
Connect a database →データベースを使う →gd 0.8.0 / REFERENCE
English | 日本語
gdは、GDScriptでCLIツール、Webサイト、Web API、定期処理、データ処理を書くための単体コマンドです。 画面表示を使わない小さな実行環境をGodotから作っています。project.godotを用意せず、1つの.gdファイルを書くだけで実行できます。
PythonやNode.jsでスクリプトを書く感覚で始められます。必要に応じて型検査やテストを加え、パッケージ、データベース、Webサーバーも使えます。完成したスクリプトは、1つの実行ファイルにまとめて配布できます。ゲームの画面や描画を作る用途にはGodot本家を使ってください。
Godot本家とあわせれば、アプリもフロントもサーバーもCLIツールも、一つの言語GDScriptで書けます。 同じスクリプトがmacOS、Linux、Windowsで動き、通信とデータベースの待ちはほかの処理を止めません。 GDExtensionでC++と直接つながります。
速度も重視しています。HTTP/2に対応し、通信を待つ間もほかの処理が進みます。文字列とJSONの処理も高速です。
配布バイナリはmacOS arm64/x86_64、Linux x86_64、Windows x86_64向けです。Linux arm64はソースからビルドできます。 ReleasesからOSに合うアーカイブを取得し、gdをPATHの通ったディレクトリへ置く方法も使えます。
curl -fsSL https://gd.progsha.com/install.sh | sh
~/.local/binへ導入します。PATHに未設定の場合だけy/Nで追加を確認します。yを選ぶと利用中のシェルに合う設定へ保存し、新しいターミナルから使えます。Linux配布バイナリにはx86_64とglibc 2.38以降が必要です。
Invoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1
導入先がPATHに未設定の場合だけy/Nで確認し、yを選ぶとユーザーのPATHへ追加します。
brew tap prog-sha/gd https://github.com/prog-sha/gd
brew install prog-sha/gd/gd
Ubuntu 24.04、Debian 13など、glibc 2.38以降のapt対応環境で利用できます。
sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://gd.progsha.com/apt/gd.asc | sudo tee /etc/apt/keyrings/gd.asc >/dev/null
sudo chmod 0644 /etc/apt/keyrings/gd.asc
echo 'deb [arch=amd64 signed-by=/etc/apt/keyrings/gd.asc] https://gd.progsha.com/apt stable main' | sudo tee /etc/apt/sources.list.d/gd.list
sudo apt update
sudo apt install gd
gd upgrade # Move to the latest release.
gd upgrade 0.8.0 # Move to a chosen version.
gd upgrade --dry-run # Show the version without installing it.
配布元のSHA-256と照合してから、実行中のgdを置き換えます。Homebrewやaptで入れたgdは、それぞれのbrew upgrade gd、apt upgrade gdで更新してください。
Python、uv、SCons、C/C++コンパイラーを用意します。実行ファイルはbin/に生成されます。
git clone --branch master https://github.com/prog-sha/gd.git
cd gd
scons platform=macos target=template_release -j8
# Linux ARM64: platform=linuxbsd arch=arm64
# Linux x86-64: platform=linuxbsd arch=x86_64
# Windows: platform=windows arch=x86_64 use_mingw=yes windows_subsystem=console
hello.gdを1つ作ります。設定ファイルやパッケージは要りません。main()が入口で、返した整数がプロセスの終了コードになります。
func main():
print("Hello, world")
return 0
gd hello.gd
実行せずに型と構文を調べるにはcheckを使います。
gd check hello.gd
ローカルファイルは@import "./settings"、導入済みパッケージは@import hello。読み込んだ名前をそのまま使います。.gdやas settingsは省略できます。
共有する値をsettings.gdに置きます。
const TITLE = "Hello"
const USER = "world"
main.gdから使います。
@import "./settings"
func main():
print(settings.TITLE, ", ", settings.USER, "!")
return 0
これでHello, world!と表示します。共有が必要になったときの書き方です。
asは、名前がぶつかるときだけ使います。GD.webなどは、importなしで使えます。パッケージの導入とバージョン固定はパッケージと配布を参照してください。
標準APIはGDにまとまっています。ファイル操作はGD.file、WebサービスはGD.webのように、用途に合わせて選びます。
| やりたいこと | 入口 | 例 |
|---|---|---|
| ファイル、文字、日時、HTTP クライアント、非同期処理 | GD | GD.file.read_text("a.txt") |
| WebサイトとWeb API | GD.web | GD.web.app() |
| SQLiteまたはPostgreSQL | GD.database | GD.database.client() |
| Redis | GD.database.redis | GD.database.redis.client() |
| TCP、UDP、TLS | GD.net | GD.net.listen_tcp("127.0.0.1", 8080) |
| メールの解析とSMTP送信 | GD.mail | GD.mail.parse_address("me@example.com") |
コマンドの使い方はgd --help、コマンドごとの引数とオプションはgd install --helpのように調べます。
APIはgd doc GD.file.read_textのように、調べたい関数や型の名前を渡します。関数名・引数・戻り値の情報は、実行プログラムから取得しています。
gd doc # Show a short guide and entry points.
gd doc manual # Read the complete manual.
gd doc GD # List the standard modules.
gd doc GD.file # file API
gd doc GD.http.fetch # Inspect the returned HTTP response.
gd doc GD.web.app # Web application
gd doc SceneTree # Inspect a public engine class.
gd doc all # List public types.
戻り値に使われる型のErr、GDWebRequestは名前だけで引きます。Node、SceneTree、TimerなどGodot由来の型は Godotのクラスリファレンスも参照してください。 手引きの言語はLC_ALLまたはLANGがjaで始まるとき日本語、それ以外は英語です。 Web版はgd.progsha.comにあり、日本語と英語を切り替えられます。
掲載例では型名を繰り返しません。:=で代入する変数は右辺から型を推論します。 注釈を省いた引数は動的型です。受け取る値や返す値の型を限定したい箇所には、型名を書けます。
スクリプト名の後ろに置いた引数はmain(argv)で受け取ります。--name=gdのようにgd自身のオプションと紛らわしい引数は、 --の後ろへ置くとスクリプトへ渡ります。
func main(argv):
for arg in argv:
print(arg)
return 0
gd main.gd apple orange
gd main.gd -- --name=gd
オプションとして解釈したいときはGD.cli.flags()を使います。--name gd、--name=gd、-name=gdのどの綴りも受けます。
func main(argv):
var flags := GD.cli.flags()
flags.flag_str("name", "world", "挨拶する相手")
var _parsed, parse_err := flags.parse(argv)
if parse_err:
print(flags.usage())
return 1
print("Hello, " + flags.get_str("name"))
return 0
外の道具はGD.cli.run()で呼びます。待つのは呼び出したGDScriptだけなので、gd serveのハンドラーの中から呼んでも他のリクエストは進みます。 --strictでは--allow-runが要ります。--allow-run=/usr/bin/gitのように相手を絞れます。
func main():
var got, err := await GD.cli.run("git", ["rev-parse", "HEAD"])
if err:
return 1
print("code=", got["code"], " out=", got["output"])
return 0
子プロセスの終了コードが0以外ならErrを返します。終了コードはvalue.code、出力はvalue.outputで読めます。時間切れやキャンセルのときも、そこまでの出力は残ります。
第3引数のoptsで挙動を変えられます。
| 名前 | 既定 | 意味 |
|---|---|---|
timeout | 0 | 完了を待つ秒数。0は無期限。時間を超えると子プロセスを終了し、Err.TIMED_OUTを返す |
output | true | 出力を集める。falseなら親の標準入出力へ直結し、集めない |
失敗する可能性がある関数は、値とErrの2つを返します。 var 値, e :=で両方を受け取れます。型は関数の宣言から推論され、eがnullでなければ失敗です。 既存の変数には値, e = call()で代入できます。先に型なしで宣言した変数はVariantのままなので、静的に型を検査するならvar 値: Tとvar e: Errを宣言します。
func main():
var text, e := GD.file.read_text("note.txt")
if e:
print(e.text())
return 1
print(text)
return 0
関数呼び出しの末尾に?を付けると、失敗時は値とErrを呼び出し元へ返します。成功時は値だけを使えます。 ?を使う関数は値とErrを返します。返却型を省くとreturnの値から第一結果を推論し、必要なら-> String, Errのように明示できます。正常時のreturn 値は、第二結果のnullを省略した形です。
func title(path) -> String, Err:
var text := GD.file.read_text(path)?
return text.strip_edges()
func main():
var text, e := title("note.txt")
if e:
print(e.note("題名を読む").text())
return 1
print(text)
return 0
ファイルを読めても、内容が空なら失敗にしたい場合は、自分でErrを作って返します。Err("説明", 種類, 追加情報)の形で、説明文、Err.INVALID_DATAなどの種類、必要な情報を指定します。次をread_message.gdに保存してください。
# Read a message and reject empty contents.
func read_message(path: String) -> String, Err:
var text := GD.file.read_text(path)?
if text.strip_edges().is_empty():
return "", Err("Message is empty", Err.INVALID_DATA, {"path": path})
return text, null
# Print the message or report the failure to the caller.
func main() -> int:
var text, err := read_message("message.txt")
if err != null:
printerr(err)
return 1
print(text)
return 0
printf 'Hello!\n' > message.txt
gd read_message.gd
printf '' > message.txt
gd read_message.gd
最初の実行はHello!を表示し、空ファイルにした後の実行はMessage is emptyというエラーを表示して終了コード1を返します。
-> String, Errは、文字列とエラーの2つを返すという宣言です。return text, null、失敗したらreturn "", Err(...)を返します。var text, err := read_message(...)で受け取り、errを確かめてからtextを使います。?がそのエラーをそのまま返します。HTTP、データベース、GD.net、ファイルなどの待つメソッドは、普通の関数呼び出しとして書けます。 待つのは呼び出したGDScriptだけで、ほかの通信やタイマーは進みます。
func main():
var res := GD.http.fetch("https://example.com/")!
print(res.status)
return 0
複数の処理を同時に始めたいときは、末尾が_asyncの版とGD.async.all()を使います。
func main():
var got = await GD.async.all([
GD.http.fetch_async.bind("https://example.com/a"),
GD.http.fetch_async.bind("https://example.com/b"),
])
for result: Array in got:
var res: GDHTTPResponse = result[0]
var e: Err = result[1]
if e:
print(e.text())
return 1
print(res.status)
return 0
| 入口 | 用途 |
|---|---|
名前_async() | 処理を始め、結果を保持するGDTaskをすぐ返す。ほかの処理を待った後でも、awaitすると通常名と同じ結果を受け取れる。cancel()で取り消せる |
GD.async.all(list) | 複数の処理を同時に進め、結果を渡した順に返す |
GD.async.spawn(fn) | 関数を裏で動かす。main()が返った後も動く |
GD.async.sleep(sec) | 指定秒だけ待つ |
1つだけ待つときはvar value, e := await GD.http.fetch_async(url)のように、通常名と同じ形で受け取れます。
先に始めた処理を、あとから順に受け取ることもできます。firstを待つ間にsecondが終わっても、結果はsecondが保持しています。
func main():
var first := GD.http.fetch_async("https://example.com/a")
var second := GD.http.fetch_async("https://example.com/b")
var a, a_err := await first
var b, b_err := await second
if a_err or b_err:
return 1
print(a.status, " ", b.status)
return 0
気を付ける点は3つです。
all()には、_async()が返したGDTaskか、上の例のように.bind()で作ったCallableを渡します。どちらも、先に終わった処理の結果を取りこぼしません。spawn()は処理を別スレッドへ移しません。大きなデータを標準モジュールで処理するときは_asyncの版を使います。main()や自分で書いた関数の中で呼びます。Array.map()へ渡す関数、_init()、メンバー変数の初期化の中では待てないので、forかGD.async.all()で書きます。ここまでの知識で、JSONを受けてSQLiteへ保存する小さなAPIを1つのスクリプトで作ります。 できあがるのは、入力を検査し、SQL文と値を分けて渡す、権限を絞って起動する開発用サーバーです。
mkdir notes-api
cd notes-api
次をmain.gdとして保存します。
# Store notes in an embedded database and expose a JSON API.
extends RefCounted
const PORT := 18080 # Development listener port on loopback.
const DB_PATH := "user://notes.sqlite3" # Writable storage isolated per user.
var app := GD.web.app()
var db := GD.database.client()
# Return notes as JSON in newest-first order.
func list_notes(req: GDWebRequest) -> GDWebResponse, Err:
var got, query_err := await GD.async.with_context_pair(req.context, db.query_async("SELECT id, title FROM notes ORDER BY id DESC"))
if query_err:
return query_err
return GD.web.json(got.rows)
# Save a validated title and return the created row.
func add_note(req: GDWebRequest) -> GDWebResponse, Err:
var body := req.valid("body")
var made, query_err := await GD.async.with_context_pair(req.context, db.query_async(
"INSERT INTO notes(title) VALUES($1) RETURNING id, title",
[body.title]
))
if query_err:
return query_err
return GD.web.json(made.rows[0], 201)
# Prepare the database and routes, then listen on loopback.
func main() -> int, Err:
db.open({"driver": "sqlite", "path": DB_PATH})?
db.query("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT NOT NULL)")?
app.route("GET", "/notes", list_notes)
app.route("POST", "/notes", add_note, [GD.web.json_body(GD.web.object_rule({
"title": GD.web.text_rule({"min": 1, "max": 120}),
}))])
app.listen(PORT, "127.0.0.1")?
print("listening on http://127.0.0.1:%d" % PORT)
return 0
上から順に読みます。
appはルーター、dbはデータベース接続です。main()が返った後もサーバーが動き続けられるよう、両方ともスクリプトの変数として持ちます。main()はまずSQLiteを開き、表を作ります。DB_PATHのuser://は、gdが利用者ごとに用意する書き込み領域です。app.route()に、HTTP メソッド、パス、そのときに呼ぶ関数(ハンドラー)を登録します。GDWebRequestを受け取り、GD.web.json()で返事を作ります。途中の?は失敗をサーバーへ返し、ステータスコード500などになります。GD.web.json_body()を付けています。本文が検証ルールに合うときだけハンドラーが呼ばれ、通った値がreq.valid("body")に入ります。$1に入れる値は、別の引数で渡します。文字列連結でSQLを組み立てません。未確認のスクリプトや外へ公開するサーバーは、権限を既定で拒否する--strictで実行します。ここでは待ち受け先をループバックの一つのポートに絞ります。 serveはmain()が返った後もプロセスを残すコマンドで、サーバーにはこれを使います。
gd check main.gd
gd --strict --allow-net=127.0.0.1:18080 serve main.gd
curl -s -X POST http://127.0.0.1:18080/notes \
-H 'Content-Type: application/json' \
-d '{"title":"gdを試す"}'
curl -s http://127.0.0.1:18080/notes
最初はステータス 201と作成した一件、次は保存済みの配列が返ります。空の題名、120文字を超える題名、 JSONでない本文は400で拒否されます。止めるときは起動したターミナルでCtrl-Cを押します。
公開環境ではこのプロセスをループバックのままTLS リバースプロキシの後ろへ置き、異常終了耐性が必要な保存先は PostgreSQLへ切り替えます。接続情報はソースへ書かず、許可した環境変数から読みます。
最初は通常実行を使います。--strictは、必要な権限を自分で設計・設定する上級者向けの実行方式です。
| 方式 | 向く場面 | 制限 |
|---|---|---|
| 通常実行 | 信頼できるソースを開発中に動かす | ファイルもネットワークも制限しない |
--strict | 未確認のスクリプト、公開サーバー | 起動ディレクトリ配下は読み取り専用で、外部の絶対パスは拒否。ネットワーク、環境変数、子プロセス、ネイティブ拡張機能、システム情報を既定で拒否 |
--strictでは、使うものを挙げて起動します。
gd --strict \
--mount store=/srv/app:rw \
--allow-net=db.example.com:5432 \
--allow-env=DATABASE_URL \
main.gd
| 指定 | 許すもの |
|---|---|
--mount name=path:r / --mount name=path:rw | 名前を付けたディレクトリの読み取り、または読み書き |
--allow-net=host:port,... | 接続と待ち受け。値を省くと全て |
--allow-env=name,... | 環境変数 |
--allow-run=command,... | 子プロセス |
--allow-ext=path,... | スクリプトが実行中に読むネイティブ拡張機能 |
--allow-sys=item,... | 機種とシステム情報 |
--deny-* | 対応するallowより優先する拒否 |
-A | ファイル以外を全て許す。開発中の一時的な利用向け |
--strictが効くのは、スクリプトを実行するrun、serve、test、task、eval、replです。checkやfmt、パッケージ操作のようにスクリプトを実行しないコマンドには影響しません。
スクリプトから見えるファイルの置き場は次の4種類です。置き場の名前をパスの先頭に書くか、絶対パスをそのまま書きます。
| 書き方 | 指す場所 | strictでの扱い |
|---|---|---|
res://a.txt | スクリプトを起動したディレクトリ | 読み取り専用 |
user://a.txt | 実行したスクリプトごとに、利用者のデータ領域に用意する書き込み領域。再起動しても残る | 読み書き可能 |
store://a.txt | --mount store=/srv/app:rwで付けた名前 | 指定した権限 |
/etc/hosts | このコンピューター上の指定した場所 | 起動ディレクトリの外なら拒否 |
迷ったら、読むだけのファイルはres://、保存するファイルはuser://へ置きます。
--mountで名前を付けます。-Aを付けてもファイルの範囲は広がりません。storeやuploadsのように、小文字の英数字と-で付けます。gdが使っている次の名前は選べません: res、user、uid、pipe、local、libgodot、tcp、unix、http、https、file、data、cache、pkg、global。--mountと絶対パスを使えません。res://かuser://へ置いてください。--allow-netのlocalhost:8080は、同じポートのIPv4 ループバック 127.0.0.0/8とIPv6 ::1も表します。*.example.com:443はその下位ホストを許します。gd serveはSceneTreeを作らない常駐用の実行方式です。通信、タイマー、await、自作Signal、GD.async.sleep()、 ツリー外Nodeのqueue_free()は動きます。仕事が無ければ次の期限か通信の通知まで眠るため、周期の調整は要りません。
| やりたいこと | 方法 |
|---|---|
| Webサーバーや定期処理を常駐させる | gd serve main.gd |
Nodeの_process()、_physics_process()、process_frame、SceneTreeTimer、高水準マルチプレイを使う | serveを付けない通常実行 |
| SceneTreeやMainLoopを継承したスクリプトを動かす | serveを付けない通常実行 |
| SceneTreeが紛れ込んでいないか開発中に調べる | gd --no-scene-tree --allow-net serve app.gd |
| 複数プロセスで待ち受ける | --workers=<n>または--workers=auto。nは1以上の整数 |
serveではNodeを継承しただけのスクリプトはツリーへ追加されません。 --no-scene-treeはSceneTreeが作られた時点で診断を出し、終了コード 1で止まります。--watchと--workersの子にも引き継がれます。
低水準の通信にはGD.netを使います。Godot本家の低水準の型も使えますが、新しいコードはGD.netで書きます。
func echo() -> int, Err:
var listener := GD.net.listen_tcp("127.0.0.1", 8080)?
var conn := listener.accept()?
var data := conn.read(65536)?
conn.write(data)?
conn.close()
return 0
GDTCPConnは読み取りと書き込みを別々の順番待ちで処理するため、複数のGDScriptから同時に呼べます。close()を呼ぶと、待っている読み書きはErr.INTERRUPTEDで終わります。リスナーの受付待ちも同じです。timeoutは延びません。TLSはGD.net.dial_tls(host, port, opts)で開きます。既定で証明書チェーンと接続先のホスト名を検証し、失敗しても平文へ戻りません。 戻り値はTCPと同じGDTCPConnです。
opts | 意味 |
|---|---|
timeout | 接続とTLSの初期通信が完了するまでの制限時間(秒) |
ca_file | 私設CA。環境変数の設定より優先する |
cert_file、key_file | クライアント認証。許可されたマウント内のファイルを対で指定する |
server_name | 証明書を照合する宛名を接続先と別にする |
next_protos | ALPN名の配列。1名は1–255 バイト、全体で65535バイトまで |
insecure_skip_verify | 検証を省く。検証不要と判断できる試験時だけ使う |
交渉結果はconnection_state()のnegotiated_protocolとversionで読めます。TLS1.2は771、TLS1.3は772です。
信頼するCAは、未指定ならmacOSとWindowsではOSの信頼設定、Linuxではシステム CA証明書の一覧です。 起動前にSSL_CERT_FILEまたはSSL_CERT_DIRを設定すると、どのOSでも指定したCAを使います。 ディレクトリの区切りはUnixで:、Windowsで;です。
サーバーがクライアント証明書を求めるときは、app.listen_tls(port, cert, key, host, opts)のoptsへclient_ca(信頼するCA証明書の一覧)とclient_authを渡します。 client_caが未指定ならシステムの信頼設定を使います。
client_auth | 動作 |
|---|---|
none | 証明書を要求しない |
request | 任意提示。検証しない |
require | 提示だけ必須。検証しない |
verify_if_given | 提示された場合だけ検証する |
require_and_verify | 検証済みの証明書を必須にする |
UDPはGD.net.listen_udp()で開きます。届いたパケットには送り主のhostとportが入っているので、そのまま返信できます。
func echo_udp() -> int, Err:
var conn := GD.net.listen_udp("127.0.0.1", 9000)?
var packet := conn.read_from()?
conn.write_to(packet.data, packet.host, packet.port)?
conn.close()
return 0
write_to()の宛先はIPアドレスで渡します。ホスト名は先にGD.net.resolve(name)?でIPアドレスにします。read_from()が1つのパケットです。受け取る大きさを超えた分は捨てられ、packet.truncatedがtrueになります。GD.net.local_addresses()で調べます。GD.mailはメールアドレスやヘッダーを解析し、SMTPサーバーへメールを送ります。
send_mailには、ヘッダーと本文を含むメール全体をバイト列で渡します。--strictでは、接続先に--allow-netが要ります。func main() -> int, Err:
var message := "From: me@example.com\r\nTo: you@example.com\r\nSubject: Hello\r\n\r\nHello\r\n".to_utf8_buffer()
GD.mail.send_mail("smtp.example.com", 587, "me@example.com", PackedStringArray(["you@example.com"]), message, {
"tls": "starttls", "timeout": 10.0,
"auth": GD.mail.plain_auth("me@example.com", "secret"),
})?
return 0
GD.fileでファイルの読み書きとパス操作をします。起動したディレクトリがres://で、絶対パスも書けます。 strictで外部ディレクトリへ書くときは--mount store=/srv/app:rwで付けた名前をstore://users.csvのように書きます。
func main() -> int, Err:
var rows := GD.data.csv_objects(GD.file.read_text("store://users.csv")?)?
GD.file.write_text("store://users.json", JSON.stringify(rows))?
return 0
ファイルの操作は、通常名でも呼び出したGDScriptだけを待たせます。Webサーバーのハンドラーから読んでも他のリクエストは進みます。 複数の操作を同時に始めるときだけ、末尾が_asyncの版を使います。
func handler(_req) -> GDWebResponse:
var body, read_err := GD.file.read_text("store://big.json")
if read_err:
return GD.web.text("読めません", 500)
return GD.web.text(body)
compileで同梱したファイルも、同じAPIで読み取り、列挙、static配信ができます。
全体をメモリへ置かず読むときはGD.file.open(path, mode)でGDFileStreamを開きます。 modeはread、write、append、read_writeで、使い終えたらclose()を呼びます。
| メソッド | 動作 |
|---|---|
read(max) | 最大max バイトを返す。少なく返ることがある。maxが正のとき、エラーがなく空ならファイルの末尾まで読み取り済み |
write(bytes) | 全て書いてバイト数を返す。途中で失敗しても第一結果に書き込み済みバイト数が残る |
同じストリームの操作は受付順、別のストリームは並列に進みます。appendはseekの後も常に末尾へ書きます。 read_bytes()も途中で失敗したときは取得済みのバイト列を第一結果に残します。 read_text()はStringに収まらない大きさの入力を切り詰めずエラーにするので、大きなファイルはバイト列かストリームで扱います。
複数のプロセスが同じファイルを更新するときはGD.file.replace_text(path, old, body)を使います。 読み取ったoldと現在の内容が同じときだけ置き換えるため、並行編集を黙って上書きしません。新規作成ではoldにnullを渡します。
| 用途 | 入口 |
|---|---|
CSV、TOML、YAML、JSONL、JSONC、XML、INI、TAR、front matter、.envのファイルを読む | GD.file.read_csv(path)など |
| 同じ形式のメモリ上の変換、JSON、エンコード・デコード、ハッシュ、HMAC、PBKDF2、HKDF、バイト列 | GD.data |
| UUIDとULID | GD.id |
| 日時の変換と計算 | GD.time |
| 文字の整形と比較 | GD.text |
| HTML エンティティ、タグ、gdhtml(Mustache構文のマイクロテンプレート) | GD.html |
| オプションと環境変数 | GD.cli |
| 配列と辞書の操作 | GD.collection |
| 数学の特殊値とビット演算 | GD.math |
| バージョンの比較 | GD.version |
| ターミナルとファイルへのログ | GD.log |
| テストの検査 | GD.test |
環境変数と.envは、読む対象で入口が分かれます。
| 読む対象 | 入口 |
|---|---|
| プロセスの環境変数 | GD.cli.env(name, fallback)、GD.cli.require_env(name)。strictでは--allow-envが要る |
.env ファイル | GD.file.read_env(path)。ファイルを読んで辞書にする |
| dotenv形式の文字列 | GD.data.env(src)とGD.data.to_env(data)。メモリ上で辞書と変換する |
メモリ上の変換は通常名がその場で計算し、_asyncの版は別のスレッドで計算します。大きな入力には_asyncを使います。 正確な一覧はgd doc GD.fileとgd doc GD.dataで引けます。形式ごとの検査と上限は、APIリファレンスの各入口の説明にあります。
GD.collectionのCallableを使う操作は、約1 msごとにほかの処理へ実行権を譲ります。 GD.logの各呼び出しは書き込み完了まで待ち、本文を切り捨てません。失敗は第二結果のErrで確認でき、GD.log.flush()でそれ以前の出力完了を待てます。
値はGD.data.json_encode(value)でJSONのバイト列にし、受け取ったバイト列はGD.data.json_decode(bytes)で読みます。 GDWebRequest.json()、GDHTTPResponse.json()、JSONLの各行も同じ規則です。
func main() -> int, Err:
var bytes := GD.data.json_encode({"id": 1, "tags": ["a", "b"]})?
var value := GD.data.json_decode(bytes)?
print(value.id)
return 0
intのまま戻ります。小数と指数表記はfloatになります。{"deterministic": true}を渡します。GD.dataはSHA-1、SHA-224/256/384/512、SHA3-224/256/384/512を返します。HMAC、PBKDF2、HKDFでは sha1、sha224、sha256、sha384、sha512、sha3-224、sha3-256、sha3-384、sha3-512から方式を選べます。 PBKDF2とHKDFは出力長を指定でき、不正な方式や表現範囲外の設定はErrとして返します。PBKDF2の繰り返す回数が1以下なら1回として計算します。
同じディレクトリにmain.gdとindex.htmlを作ります。一方のルートでHTMLテンプレートに挨拶を埋め込み、もう一方で同じデータをJSONとして返します。
main.gd:
# Serve a greeting as an HTML page and a JSON response.
var app := GD.web.app()
# Build the shared response data from the requested name.
func greeting(req: GDWebRequest) -> Dictionary, Err:
var name := req.query.get("name", "world")
if not name is String:
return {}, Err("name must be text", Err.INVALID_DATA)
return {"name": name, "message": "Hello, " + name + "!"}
# Render the page with escaped template values.
func home(req: GDWebRequest) -> GDWebResponse, Err:
return GD.web.view("index.html", greeting(req)?)
# Return the same data as JSON.
func hello(req: GDWebRequest) -> GDWebResponse, Err:
return GD.web.json(greeting(req)?)
# Listen locally, using an optional port argument.
func main(args):
var port := 8080 if args.is_empty() else int(args[0])
app.route("GET", "/", home)
app.route("GET", "/api/hello", hello)
app.listen(port, "127.0.0.1")!
print("http://127.0.0.1:", app.port())
return 0
index.html:
<!doctype html>
<!-- Display a greeting and let visitors choose the name. -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{message}}</title>
<style>
body { max-width: 36rem; margin: 4rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; line-height: 1.6; }
input, button { padding: .6rem; font: inherit; max-width: 100%; box-sizing: border-box; }
</style>
</head>
<body>
<h1>{{message}}</h1>
<form action="/" method="get">
<label>Your name <input name="name" value="{{name}}"></label>
<button type="submit">Say hello</button>
</form>
<p><a href="/api/hello?name={{name}}">View the JSON response</a></p>
</body>
</html>
そのディレクトリで実行します。
gd serve main.gd
http://127.0.0.1:8080/?name=Aliceを開くと、{{message}}へ「Hello, Alice!」を埋め込みます。/api/hello?name=Aliceは{"name":"Alice","message":"Hello, Alice!"}を返します。テンプレートの値はHTMLの文脈に応じてエスケープされます。
serveはmain()が返ったあとも待ち受けを続けます。終了はCtrl+Cです。
route(method, pattern, handler)でHTTP メソッドとパスをハンドラーへ結びます。patternの:nameはreq.params["name"]に入ります。 HEADの要求にはGETのルートで応えます。パスは合うのにメソッドが違う要求には405を返します。 ハンドラーはGDWebRequestを受け取ります。本文はreq.read()、bytes()、text()、json()、save()で必要な分だけ読みます。 HTMLのフォームから届く本文はGD.http.decode_query(req.text()?)で辞書にします。
ハンドラーが返した値が返事になります。return GD.web.json(data)のように、下の表の値をそのまま返します。
途中の操作が失敗したら、call()?でそのErrを返します。Errは表の最後の行のステータスコードになります。返事を自分で決めたいときはapp.on_error(handler)を登録します。
| 返した値 | 返事 |
|---|---|
GD.web.html(body)、GD.web.view(path, data) | HTML |
GD.web.json(data) | JSON |
GD.web.text(body)、GD.web.bytes(body, type) | テキスト、任意のメディアタイプ |
GD.web.stream(producer) | 本文を少しずつ送信する。「Webの運用と高度な機能」を参照 |
GD.web.redirect(to) | 302。toは同じサイト内のパスに限り、他所へ送るときはawayをtrueにする |
GD.web.not_found() | 404 |
| 文字列 | テキスト/plainの200 |
bodyを持つ辞書 | 手書きの返事。status、type、headersも指定できる |
bodyを持たない辞書 | JSONの200 |
null | 204 |
失敗のErr | 種類に応じたステータスコード。INVALID_DATA → 400、UNAUTHENTICATED → 401、PERMISSION_DENIED → 403、NOT_FOUND → 404、LIMITED → 429、UNSUPPORTED → 501、TIMED_OUT → 504、他は500(いずれもErrの定数) |
返事は次のように調整できます。
GD.web.text("見つかりません", 404)のように第2引数で変えます。bytesはメディアタイプの後ろに書きます。GD.web.header(reply, name, value)で返事にヘッダーを足します。GD.web.guard(reply)でContent-Security-Policyなどの防御ヘッダーをまとめて足します。app.show_errors(true)で表示できます。req.queryの値は文字列とは限りません。上の例のようにis Stringで確かめてから使います。req.pathは%20などを元の文字へ戻したパスです。届いたままの文字列はreq.targetで読めます。ルーターには次も登録できます。
| 登録 | 用途 |
|---|---|
app.static("/assets", "res://public") | 接頭辞以下のGETとHEADをディレクトリのファイルで返す。メディアタイプは拡張子から決め、ディレクトリの外は返さない。/のindexはrouteで書く |
app.group("/api", [middleware]) | 共通接頭辞とミドルウェアを持つルートグループ。戻り値にroute()とuse()がある |
app.fallback(handler) | どのルートにも一致しない要求。404ページをここで返す |
app.on_error(handler) | ハンドラーが失敗を返したときの返事 |
app.after(handler) | 返事を送る前の加工。func(req, reply)で受け、ヘッダーを足して返す |
ミドルウェアは、ハンドラーの前に呼ばれる関数です。GDWebRequestを受け取り、nullを返すと次へ進み、返事を返すとそこで止まります。 handle(req)を持つオブジェクトも使えます。後段へ渡す値はreq.keep(name, value)で置き、req.kept(name)で読みます。
| 登録 | 掛かる範囲 |
|---|---|
app.pre(mw) | ルート選択の前。全要求 |
app.use(mw) | ルート選択の後。全ルート。req.paramsを読める |
group.use(mw) | そのグループのルート |
app.route(method, pattern, handler, [mw]) | そのルートだけ |
入力検査もミドルウェアです。GD.web.json_body(rule)、GD.web.query(rule)、GD.web.params(rule)が本文、クエリ、パスの値を検査し、 通った値をreq.valid("body")、req.valid("query")、req.valid("params")に入れます。 検証ルールはGD.web.text_rule()、int_rule()、number_rule()、bool_rule()、list_rule()、object_rule()で組み、 GD.web.optional()とGD.web.one_of()で省略と選択肢を表します。クエリとparamsの値は文字列なのでtext_rule()で検査し、必要ならto_int()で変換します。
var app := GD.web.app()
func show(req) -> GDWebResponse, Err:
var params := req.valid("params")
return GD.web.json({"id": params.id})
func main():
app.route("GET", "/posts/:id", show, [GD.web.params(GD.web.object_rule({"id": GD.web.text_rule({"min": 1, "max": 20})}))])
app.listen(8080)!
return 0
組み込みのミドルウェアはGD.web.sessions()、GD.web.csrf()、GD.web.jwt()、GD.web.rate()です。認証の節で使います。
ページが増えてきたらHTMLをテンプレートファイルへ出し、GD.web.view(path, data)で描画します。 テンプレートはgdhtml(Mustache構文のマイクロテンプレート)で、{{name}}、{{{html}}}、#if、#unless、#each、 #with、else、{{> header}}を扱います。views/page.htmlから{{> header}}を使うと、 同じ階層のviews/partials/header.htmlを読みます。
<!-- views/page.html -->
{{> header}}
<main><h1>{{title}}</h1></main>
<!-- views/partials/header.html -->
<header><a href="/">gd app</a></header>
func page(_req) -> GDWebResponse, Err:
return GD.web.view("views/page.html", {"title": "Top"})
二重括弧の値は、置かれた位置から文脈を判定してエスケープします。テンプレートの作者を信頼し、差し込む値を信頼しない前提です。
| 文脈 | 扱い |
|---|---|
| HTML本文、引用・未引用属性、属性名 | HTML エスケープ |
href="{{url}}" | 相対URLとhttp、https、mailtoを通す。data-hrefも同じ |
href="/work/{{path}}"、href="/?q={{query}}" | パスは区切りを保って正規化、クエリはpercent エスケープ |
onclick、script本文 | JSON化し、application/jsonでも</script>が構造を壊さない形にする |
style | 安全な単独CSS値とCSS文字列・URLを通す |
| 危険なURL、srcset、CSS値、属性名 | 画面全体を失敗させず、#ZgdunsafeZまたはZgdunsafeZへ置き換える |
{{{html}}}はエスケープしない唯一の入口で、HTML本文以外では使えません。固定HTMLか十分に検査済みの値だけを渡してください。eachの反復が異なる文脈で終わるテンプレート、閉じていないタグ、曖昧なURLやJavaScript文脈は描画の失敗になります。同じテンプレートを何度も描画するサーバーでは、起動時にGD.html.template(source, partials)?で一度だけ解析し、 返った値のexecute(data)?を各要求から呼びます。解析結果は不変で、複数の要求から同時に使えます。 execute_bytes(data)?はUTF-8のバイト列を直接作るので、GD.web.bytes(body, "text/html; charset=utf-8")でそのまま返せます。
ログインの状態はGD.web.sessions()で持ちます。issue(value)でセッション IDを作り、cookie(id)の値をSet-Cookieで返します。 同じstoreをミドルウェアとして付けたルートでは、CookieのIDに対応する値がreq.kept("user")に入り、無ければ401になります。 ミドルウェアの設定が不正なら生成関数はnullを返し、app.use()やルートに渡した場合はapp.listen()が設定エラーを返します。
var app := GD.web.app()
var sessions := GD.web.sessions()
func login(req: GDWebRequest) -> GDWebResponse, Err:
var form := GD.http.decode_query(req.text()?)?
var user := str(form.get("user", [""])[0])
if user.is_empty():
return GD.web.text("user is required", 400)
var reply := GD.web.redirect("/me")
return GD.web.header(reply, "Set-Cookie", sessions.cookie(sessions.issue(user)?))
func me(req) -> GDWebResponse, Err:
return GD.web.text("hello, " + str(req.kept("user")))
func main():
app.route("POST", "/login", login)
app.route("GET", "/me", me, [sessions])
app.listen(8080)!
return 0
cookie(id)はSecureとHttpOnly付きで作ります。TLSなしの開発中に届かない場合はcookie(id, false)にします。 ログアウトはdrop(id)とclear_cookie()で行います。セッションはプロセス内で持つため、--workersで複数プロセスにするときはJWTか外部の保存先を使います。
Cookieで認証する書き込み経路にはGD.web.csrf()を付けます。GET、HEAD、OPTIONS以外はブラウザーの Sec-Fetch-Site: same-originが必要です。古いブラウザーやブラウザー以外のクライアントも受ける場合に GD.web.csrf({"allow_missing": true})を選び、別のトークン検証を組み合わせてください。
var app := GD.web.app()
var sessions := GD.web.sessions()
func save_email(_r):
return "saved"
func main():
app.route("POST", "/account/email", save_email, [GD.web.csrf(), sessions])
app.listen(8080)!
return 0
JWTをログインセッションに使う場合は、パスワード変更やログアウトで既発行トークンを失効させます。 checkは署名と標準クレームの検証後に呼ばれ、trueを返したときだけ認証を通します。 例えばトークンへ利用者のverを入れ、パスワード変更時に保存済みバージョンを増やします。 複数ワーカーでは各プロセスの辞書でなく、共有DBから同期したキャッシュなどで照合します。
func token_auth(key, versions):
return GD.web.jwt(key, {"check": func(claims):
return versions.get(claims.get("sub", ""), -1) == claims.get("ver", -2)
})
リバースプロキシの後ろでIP単位に制限するときは、そのプロキシのIPまたはCIDRをtrusted_proxiesへ明示します。 gdはX-Forwarded-Forの右端から信頼済みプロキシを除き、最初の未信頼IPをkeyにします。 未指定のときと未信頼の接続元からのX-Forwarded-Forは無視するため、クライアント自身によるIP偽装を許しません。 IPv4とIPv4-mapped IPv6は別物として照合するので、mapped アドレスを信頼する場合はIPv6のCIDRを指定します。zone付きのプロキシ設定は拒否します。
var per_ip := GD.web.rate({"limit": 60, "trusted_proxies": ["127.0.0.1", "172.18.0.0/16"]})
制限を通過した応答と429応答にはX-RateLimit-LimitとX-RateLimit-Remainingが付きます。429応答には、再試行までの秒数を示すRetry-Afterも付きます。
終了待ちはapp.shutdown(context)を使います。新規受付とkeep-aliveを止め、処理中リクエストの完了を待ちます。 期限を越えた場合はErr.TIMED_OUTを返しますが、処理中リクエストは強制終了しません。 直ちに全接続を閉じる必要がある場合にapp.stop()を使います。
func close(app: GDWebApp):
var context := GD.async.context().with_timeout(10.0)
var _stopped, stop_err := app.shutdown(context)
if stop_err:
app.stop()
ハンドラーではreq.contextからリクエストの完了と切断を受け取れます。 with_cancel()とwith_timeout()は親を変更せず子のコンテキストを返し、親の打ち切りは子へ伝わります。 HTTP、データベース、プロセスなどの二値の待ちを打ち切れるようにするには、コンテキストを先頭に渡してwith_context_pair()で包みます。一値の処理にはwith_context()を使います。 処理が先に終わればその結果を返し、コンテキストが先に終われば処理を取り消します。
func load(req: GDWebRequest, db: GDDatabaseClient) -> Variant, Err:
return await GD.async.with_context_pair(req.context, db.query_async("SELECT * FROM posts"))
大きな本文や長いハンドラーを扱うときは、待ち受け前にlimits()で上限を明示します。
func main():
var limited_app := GD.web.app()
limited_app.limits({"header_bytes": 1048576, "header_values": 500, "header_timeout": 15.0, "body_timeout": 10.0, "job_timeout": 30.0, "jobs": 128})
return 0
1 GBのZIPを受ける場合は要求ごとの上限を置き、書き込み可能なマウントへ逐次保存します。
func main():
var app := GD.web.app()
app.limits({"body_timeout": 600.0})
app.route("POST", "/upload", func(req: GDWebRequest) -> GDWebResponse, Err:
req.limit(1000 * 1000 * 1000)?
req.save("uploads://package.zip")?
return GD.web.text("saved")
)
var _server, listen_err := app.listen(8080, "127.0.0.1")
return 0 if listen_err == null else 1
gd --strict --allow-net=127.0.0.1:8080 --mount=uploads=/srv/uploads:rw serve main.gd
本文の読み方で、使うメモリが変わります。
| 読み方 | メモリの使い方 |
|---|---|
read()、save() | 少しずつ読む。save()は全体をメモリへ置かない |
bytes()、text()、json() | 残りの本文全体をメモリへ読む。一度読んだ本文は保持するので、何度呼んでも同じ内容を返す。大きな本文にはsave()を使う |
req.limit(bytes) | その要求の本文の上限。超えると、読んだ操作が失敗する |
req.limit()を置きます。limits()のheader_bytesで変えられます。GD.web.stream(producer, length=-1, type="application/octet-stream", status=200)は、producer(writer)がGDWebWriterへ書いた分だけ送ります。 全体をメモリに結合しません。本文を生成する関数の中でawaitでき、voidまたは二値を返して終わります。
GDWebWriter | 動作 |
|---|---|
write(data, offset=0, count=-1) | バイト列の範囲を送り、受け付けたバイト数を返す。送信が詰まっていれば進むまで待つ |
write_text(text, offset=0, count=-1) | 文字列の範囲をUTF-8で送る。offsetとcountの単位は文字、結果の単位はバイト |
flush() | それまでのwriteの送信完了を待つ。切断はここのエラーとreq.contextのキャンセルでわかる |
lengthは送るバイト数です。宣言と実際が合わないと接続を閉じます。不明長(-1)はHTTP/2でDATA フレーム、HTTP/1.1でchunked、HTTP/1.0で接続終了が終端になります。req.contextのキャンセルを確認してください。HTTPSはapp.listen_tls(8443, "cert://chain.pem", "cert://key.pem", "127.0.0.1")で開始し、第二結果のErrを確認します。 証明書のディレクトリは--mount cert=/path/to/certs:rで読み取り専用にします。PEM形式の証明書チェーンと暗号化されていない秘密鍵を渡します。 鍵の検証に失敗したときはポートを開きません。
TLS 1.2と1.3に対応し、ALPNでHTTP/2とHTTP/1.1を選びます。HTTP/2の各ストリームは独立に進み、一つのキャンセルは他のストリームを閉じません。 header_timeoutは完了していないTLSの初期通信にも適用されます。クライアント証明書の要求は「TCPとUDP」のTLSの表を参照してください。
GD.data.gzip_writer(writer, level=-1)は、書いたバイト列をgzipにして出力先へ渡すGDGzipWriterを作ります。 出力先にはGDFileStream、TCP接続、GDWebWriterを使えます。全体をメモリに貯めません。
| 項目 | 内容 |
|---|---|
| メソッド | write(bytes)、flush()、close()、reset(writer)。どれも値とErrを返す |
level | -2(Huffmanのみ)、-1(既定)、0..9 |
close() | gzipの末尾を完成する。出力先は閉じない |
reset(writer) | エラーを消し、同じlevelで使い回す |
header | name、comment(NULを含まないLatin-1)、extra(65535 バイトまで)、mod_time(0〜4294967295のUnix秒)、os(既定255)。最初の書き込みより前に設定する |
HTTPで返すときはGD.web.header(GD.web.stream(producer), "Content-Encoding", "gzip")を返し、本文を生成する関数の中で圧縮器を作って書き、close()の結果を返します。 Accept-Encodingの確認とVaryの設定は呼び出し側で行います。秘密情報と外部入力を一緒に圧縮せず、圧縮済みの本文や部分応答には使わないでください。
IPv6のlocalhostだけで待ち受けるにはapp.listen(8080, "::1")!を指定します。strictでは--allow-net=[::1]:8080、接続先はhttp://[::1]:8080/です。 ::1と127.0.0.1は別の待ち受けで、全インターフェースを示す::とも異なります。
空きポートをOSに選ばせる場合はapp.listen(0)の直後にapp.port()を読みます。待ち受けを保持したまま番号を得るので、他のプロセスに取られません。 待受け開始後のソケット障害はapp.serve_error()で確認できます。一時的な資源不足では短く待って再試行し、継続できない障害では待受けを閉じます。 strictでは選ばれるポートを事前に限定できないため、--allow-net=127.0.0.1のようにホスト全体を許可します。 GD.net.free_port()とis_free()は診断用の瞬間的な確認で、その番号を確保する機能ではありません。
GD.http.fetch()とGD.webの各関数に辞書で渡す設定と、その既定値です。時間は秒、大きさはバイトです。
| 入口 | 設定と既定 | 意味 |
|---|---|---|
GD.http.fetch | method="GET", headers={}, body=null | HTTP メソッド、送信ヘッダー、送信本文 |
| 同上 | timeout=0.0, max_body=0 | 要求全体の秒と応答本文のバイト。0は上限なし。新規TCP接続は30秒、TLS初期通信は10秒が既定 |
| 同上 | save="", sha256="" | 2xx 本文をsaveへ逐次保存し、返却本文は空。sha256はsave必須の64桁16進数で、一致した完了ファイルだけを置く |
| 同上 | authority="host:port" | CONNECTだけのリクエストの送信先 |
GDWebApp.limits | jobs=0, job_timeout=0.0 | 保持する非同期ハンドラー数と秒。0は無制限 |
| 同上 | header_timeout=0.0, body_timeout=0.0 | リクエストヘッダー/bodyを受け終える秒。0は無期限 |
| 同上 | header_bytes=1048576, header_values=2147483647 | リクエスト lineを含むヘッダー バイトと、ヘッダー行数 |
GD.web.jwt_sign | ttl=900 | iat/expを補う秒。0は自動付与しない |
GD.web.jwt / jwt_verify | leeway=0.0, require_exp=true | 時刻許容秒とexp必須化 |
| 同上 | iss="", aud="", keep="jwt" | 空でない場合のissuer/audience一致と保持名 |
| 同上 | check=Callable() | 署名検証後にクレームを受け取る失効判定。指定時は真だけを許可 |
GD.web.sessions | total=1024, per_user=3 | プロセス内の全セッション数と同一ユーザー数 |
| 同上 | idle=1800, life=43200 | 操作がない場合の有効期間と、セッション全体の有効期間(秒) |
| 同上 | cookie="sid", keep="user" | Cookie名とリクエスト内の保持名。Cookie名はASCIIのトークン文字 |
GD.web.rate | limit=60, window=60.0 | keyごとの最大連続回数と、その回数分を補充する時間(秒) |
| 同上 | expires=180.0 | 最後の要求からkeyを解放するまでの秒数 |
| 同上 | keys=0, key=Callable() | プロセス内で保持するkey数とkey選択関数。0は無制限。明示した保持枠が満杯なら期限が最も早いkeyを追い出す |
| 同上 | trusted_proxies=PackedStringArray() | 転送元IPを信頼するプロキシのIPまたはCIDR |
GD.web.csrf | allow_missing=false | 状態変更でFetch Metadataが無いクライアントを許すか |
GD.web.text_rule | min=0, max=4096 | テキストの文字数 |
GD.web.int_rule | min=-9223372036854775808, max=9223372036854775807 | 64ビット整数の範囲 |
GD.web.number_rule | min=-1e308, max=1e308 | 有限浮動小数の範囲 |
GD.web.list_rule | min=0, max=1024 | 要素数 |
GD.web.object_rule | extra=false | 未定義フィールドを残すか |
GDWebApp.limitsは表にある6つの設定名だけを受け、綴り違いやbody_limitを誤りとして拒否します。
範囲外の値は設定時に失敗します。受け付ける範囲は、APIリファレンスの各関数の説明にあります。
GD.database.client()が返すクライアントは、SQLiteとPostgreSQLを同じ書き方で扱います。 ローカル開発は組み込みSQLite、本番はPostgreSQLという切り替えは、open()に渡すdriverで行います。
func main() -> int, Err:
var local := GD.cli.env("DB_DRIVER", "sqlite") == "sqlite"
var db := GD.database.client()
db.open({
"driver": "sqlite" if local else "postgres",
"path": "user://app.sqlite3",
"host": "127.0.0.1",
"database": "app",
"user": "app",
"password": GD.cli.env("PGPASSWORD", ""),
})?
db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")?
db.query("INSERT INTO users (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", [1, "ada"])?
var out := db.query("SELECT id, name FROM users WHERE id=$1", [1])?
print(out.rows[0].name)
db.close()
return 0
表の作成もINSERTもSELECTもquery()一つで送ります。受け取るのはcolumns、rows、tagを持つ辞書で、 rowsは列名を鍵にした辞書の配列です。上の例ならout.rows[0].nameがadaになります。 SQLに入れる値は、$1、$2に対応する順番で渡します。両ドライバーで同じ書き方です。SQLは変換しないため、両方で通るSQLを使います。
| メソッド | 用途 |
|---|---|
query(sql, args) | 結果を全部集めて返す |
query_row(sql, args) | 先頭1行だけ返す。行が無ければErr.NOT_FOUND |
query_rows(sql, args) | GDDatabaseRowsを開き、1行ずつ読む。大量の結果向き |
stats() | 接続数、使用中、空き、待ち回数、待ち時間、接続を閉じた理由別の累積数 |
query_rows()はwhile rows.next()で進め、scan()で列名付きの辞書、values()で列順の配列を得ます。 next()がfalseになったらerr()を調べます。途中で止める場合はclose()を呼びます。
func list_users(db: GDDatabaseClient) -> Variant, Err:
var rows := db.query_rows("SELECT id, name FROM users ORDER BY id")?
while rows.next():
var user := rows.scan()?
print(user.id, " ", user.name)
if rows.err() != null:
return null, rows.err()
return null
制約違反では第二結果のe.infoにプログラムでの判定用の情報が入ります。violationはduplicate、not_null、foreign_keyのいずれか、 columnsは関係する列名です。PostgreSQLではcode、table、constraintもサーバーが返した場合に入ります。 値そのものはinfoへ残しません。SQLite自身が報告した失敗ではsource="sqlite"と拡張source_codeを保ちます。 SQLiteのforeign keyエラーメッセージには列名が無いため、その場合のcolumnsは空です。
func save(db: GDDatabaseClient) -> void:
var _saved, e := db.query(
"INSERT INTO users(id,name) VALUES($1,$2)",
[1, "ada"])
if e and e.info.get("violation") == "duplicate":
var columns := e.info.get("columns", PackedStringArray())
print("重複した列: ", columns)
複数の更新をまとめて確定または取り消したいときはtransaction()を使います。渡した関数には、専用の接続を使う GDDatabaseTxが渡ります。コールバックの第二結果がnullならコミットし、Errならロールバックします。
func save(db: GDDatabaseClient, id: int, title: String) -> Variant, Err:
return db.transaction(func(tx: GDDatabaseTx) -> int, Err:
tx.query("INSERT INTO posts(id,title) VALUES($1,$2)", [id, title])?
tx.query("UPDATE counters SET value=value+1 WHERE name='posts'")?
return id
)
txだけでSQLを実行します。元のdb.query()はこのトランザクションに入りません。txも新しいSQLを受け付けません。PostgreSQLで、同時に走る別のトランザクションとぶつかって失敗する場合(SQLSTATE 40001)は、serialize()でやり直せます。
transaction()と同じ形で、やり直すたびに新しいトランザクションで呼ばれます。func increment(db: GDDatabaseClient, id: int) -> int, Err:
var saved, e := db.serialize(func(tx: GDDatabaseTx) -> int, Err:
tx.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")?
tx.query("UPDATE counters SET value=value+1 WHERE id=$1", [id])?
return id
)
return saved, e
テーブル構成を順番に適用するときは、SQLをセミコロンで分割せず、SQL文の配列をmigrate()へ渡します。 途中の一文が失敗すると全体をロールバックし、成功時は適用した文の数を返します。 バージョンとチェックサムはアプリケーション側で管理します。
func migrate(db):
return db.migrate([
"CREATE TABLE posts(id INTEGER PRIMARY KEY, title TEXT NOT NULL)",
"CREATE INDEX posts_title ON posts(title)",
])
| 項目 | SQLite | PostgreSQL |
|---|---|---|
| 向く用途 | ローカル開発、単一プロセス | 本番、異常終了耐性、複数ワーカー |
| 接続 | クライアントごとに一つ。変更履歴と一時表はメモリに置く | 必要な接続だけ作るプール。pool=25のように最大数を指定できる |
| 追加の入口 | 短い処理をその場で行うGD.database.sqlite.open() | まとめ送り、配列、JSONBを使うGD.database.postgres |
| 注意 | 永続DBはrollback journalで未完了の書込みを回復する。既存の-wal、-shmは通常のSQLiteでチェックポイントしてから開く | ループバック以外のホストではTLS証明書とホスト名を既定で検証。ループバックはTLSなしが既定 |
GD.database.postgres.client()とGD.database.redis.client()のopen()はopen(host, port, opts)の形で、接続先を引数に取ります。
同じクライアントのquery()は受付順に実行します。別のクライアントは並行に進みますが、同じデータベースファイルへの書き込みはSQLiteのロックに従います。 GD.database.sqlite.open()が返すGDSQLiteDBとGDSQLiteStatementは、呼び出し元でそのまま実行する同期APIです。 短い処理だけに使い、同時利用はしないでください。並行処理にはGDDatabaseClientを使います。
接続はプールが必要な分だけ作り、使い終わると戻します。ふだんは接続を意識せずquery()を呼ぶだけです。空きが無いときは順番に待ちます。
| やりたいこと | 方法 |
|---|---|
| 複数のSQLを1つのまとまりで実行する | BEGINを自分で送らずtransaction()を使う |
| 複数のSQLをまとめて送る | query_many、fetch_many、exec_many |
| 重複登録を見分ける | Err.ALREADY_EXISTS。細かい原因はe.info.codeのSQLSTATEで調べる |
| 接続が足りているか調べる | stats()のwait_count(接続待ちの回数) |
| 認証方式を固定する | auth="scram"。auth="md5"は古いサーバー用 |
列の値は次の型で届きます。
| 列の型 | 受け取る値 |
|---|---|
real、double precision | float |
numeric | 桁を失わないよう文字列 |
json、jsonb | 辞書や配列。整数はintのまま |
int[]、text[]などの配列 | 同じ要素型のArray。nullと入れ子も保つ |
キャンセルや期限切れになった問い合わせは接続ごと閉じます。サーバー側のSQLがすぐ止まるとは限りません。文字コードはUTF-8です。
RedisはGD.database.redis.client()で使います。コマンド名と引数を分けてquery()へ渡します。
func main() -> int, Err:
var redis := GD.database.redis.client()
redis.open("127.0.0.1", 6379)?
redis.query("SET", ["greeting", "hello"])?
print(redis.query("GET", ["greeting"])?)
redis.close()
return 0
| やりたいこと | 方法 |
|---|---|
| 値が無いことを見分ける | GETはErr.NOT_FOUNDを返す |
| 複数のコマンドをまとめて送る | pipeline(cmds)。結果は送った順のArray |
| 多くの要求から同時に使う | GD.database.redis.pool()。接続は最初のquery()で作る |
MULTI、WATCH、SELECT、購読を使う | プールではなく専用のGDRedisClientを使う |
| 期限を決める | open()のtimeout(秒) |
TLSの選び方はPostgreSQLと同じです。
open()に辞書で渡す設定と、その既定値です。
| 入口 | 設定と既定 | 意味 |
|---|---|---|
GDDatabaseClient.open | driver="postgres", path="" | ドライバーとSQLiteのパス。user://、--mountで書き込みを許可した名前、:memory:のどれか。--strictでなければres://も使える |
| 同上 | host="127.0.0.1", port=5432 | PostgreSQLの接続先 |
| 同上 | pool=0 | PostgreSQL最大接続数。0は上限なし、SQLiteでは使わない |
| 同上 | max_rows=0, max_bytes=0 | query()が集める1結果の行数とバイト。0は無制限。query_rows()には適用しない |
GDPostgresClient.open | user="postgres", database="postgres", password="" | 認証とDB名 |
| 同上 | connect_timeout=0.0, timeout=0 | 接続と問い合わせの秒。プールの接続待ちも問い合わせ時間に含む。0は無期限。必要なら各期限を設定する |
| 同上 | auth="any", allow_cleartext_password=false | auth="scram"/"md5"で方式固定。平文パスワード応答は明示時のみ |
| 同上 | tls=<hostで決定>, ca="" | 外部ホストはverify-full、ループバックはdisable。CA ファイルは明示時だけ |
GD.database.sqlite.open | busy_ms=0, max_ms=0, foreign_keys=false | ロック待ちと実行期限のミリ秒。busy_ms=0は競合を即時通知し、max_ms=0は実行期限なし。外部キー検査は明示して有効にする |
| 同上 | max_rows=0, max_bytes=0 | 1結果の行数とバイト。0は無制限 |
GDRedisClient.open | password="", dial_timeout=5, read_timeout=5, write_timeout=5 | パスワードと接続・読取り・書込み期限の秒。各期限の明示0は無期限。timeoutを指定すると三つをまとめて設定でき、個別指定が優先される |
| 同上 | tls=<hostで決定>, ca="" | PostgreSQLと同じTLS選択 |
GD.database.postgres.pool | size既定0、0または1..2147483647 | 0は上限なし。接続は必要になった分だけ作る |
GDPostgresPool.open | max_idle=2 | 仕事を終えた後に保持する接続数。0は保持せず、最大接続数を超えない |
GD.database.redis.pool | size既定0、0..2147483647 | 最大接続数。0はCPU数の10倍。同時に作る接続は最大接続数まで |
GDRedisPool.open | pool_timeout=read_timeout+1.0(読取り期限が0なら30秒)、conn_max_idle_time=1800 | 接続の空きを待つ期限と、返却後に再利用できる期間。各設定の明示0は無期限。期限を過ぎたidle接続は次の貸出時に閉じる |
長いRedis問い合わせが必要な場合は、read_timeoutを明示して期限を延ばせます。
max_rowsまたはmax_bytesを越えたquery()は、その問い合わせだけを失敗にします。 期限切れや壊れた応答で順序を失った場合は接続全体を閉じます。
範囲外の値は設定時に失敗します。受け付ける範囲は、APIリファレンスの各関数の説明にあります。
決まった時刻に一度だけ動かす仕事は、普通のスクリプトとして書き、OSのcronやsystemd タイマーから呼びます。 gd側に常駐の仕組みは要りません。
func collect() -> int, Err:
var now := GD.time.to_iso(GD.time.now())
GD.file.append_text("store://log.txt", now + "\n")?
return 0
func main() -> int, Err:
collect()?
return 0
gd --strict --mount store=/var/lib/app:rw collect.gd
自分で間隔を持って回り続ける仕事は、GD.async.spawn()へ渡してgd serveで常駐させます。 spawn()へ渡した処理はmain()が返った後も動き続けます。
func every(sec, fn):
while true:
await GD.async.sleep(sec)
fn.call()
func collect():
print(GD.time.to_iso(GD.time.now()))
func main():
var _job := GD.async.spawn(every.bind(60.0, collect))
return 0
gd serve schedule.gd
止めるときはプロセスを終わらせます。Webサーバーと同じ常駐なので、ここでもserveが必要です。
本体を小さく保ち、外部サービス固有の機能は必要なプロジェクトだけへGDScript パッケージまたはGDExtensionとして加えます。
| 入口 | 用途 | 導入 |
|---|---|---|
Discord | DiscordのGatewayとRESTを使う、GDScriptだけで書かれたテキストBot | gd add @gd/discord |
GDSupabase | DatabaseとAuthのクライアント | gd add ext:@gd/supabase |
公開中のパッケージはパッケージ一覧で探せます。任意で導入するため、本体から生成するAPIリファレンスには含まれません。
gd addで入れた拡張は起動時に信頼して読み込むため、読み込み許可のオプションは要りません。--strictでは接続先の--allow-netが必要です。--allow-extと--deny-extが効くのは、スクリプトが実行中にGDExtensionManager.load_extension()で読む場合です。gd.lockで固定してコミットしてください。他の人が公開したパッケージを使うときは、gd initでgd.jsonを作ってから追加します。公開中のパッケージはパッケージ一覧かgd searchで探せます。
gd init
gd add hello
| やりたいこと | コマンド |
|---|---|
| 探す | gd search discord |
| 追加する | gd add hello(gd install helloも同じ) |
| スコープや版の範囲を指定する | gd add @gd/hello@^0.8.0 |
| 呼び名を決めて追加する | gd add greet @gd/hello |
| ネイティブ拡張を追加する | gd add ext:@gd/supabase |
| URLや手元のディレクトリから追加する | gd add util https://example.com/util.gd、gd add ../mylib |
| 別の環境で同じ版を復元する | gd install --frozen |
| 新しい版を調べる、上げる | gd outdated、gd update |
| 外す | gd uninstall hello |
| 入れたものを一覧する | gd info |
依存はgd.json(何を使うか)とgd.lock(どの版を使うか)に記録されます。両方をコミットしてください。引数なしのgd installはgd.jsonの依存を復元します。--frozen・--cached-only・--syncはこの復元で使います。
入れたパッケージは、スクリプトの先頭で@import 呼び名と書いて読み込みます。
@import hello
pkg://<呼び名>/)に置かれ、プロジェクトへは複製しません。gd.jsonに書いた依存がキャッシュに無ければ、最初の実行で取得します。--strictでは登録所への--allow-netが要ります。gd add helloのような短い名前は登録所で探します。同じ名前が2つ以上あるときは、どれにするか尋ねます。gd addの既定の呼び名は、パッケージ名の-と.を_にした識別子です。エンジンクラスやキーワードと同じ呼び名は断ります。gd.jsonとgd.lockです。gd initはpkg/を.gitignoreへ書きます。--frozenはロックを変更しません。オフラインの配布先では、ネットワークのある環境で先に取得し、--cached-onlyを併用します。gd install -gは、パッケージやスクリプトをmy-toolのようなコマンドとして導入します。作業中のプロジェクトのgd.jsonとgd.lockは変更しません。
gd install -g tool # Install a published package by its short name.
gd install -g @scope/tool@1.0.0 # Choose the scope and version.
gd install -g --name my-tool ./tool.gd # Install a local script.
gd uninstall -g my-tool
| 指定 | 意味 |
|---|---|
-n / --name | コマンド名。省略するとパッケージ名かスクリプト名(main.gdやmod.gdなら親ディレクトリ名) |
--root <dir> | 導入先。省略するとGD_INSTALL_ROOT、それも無ければ既定のキャッシュ。その中のbin/をPATHへ追加する |
-f / --force | 導入済みのコマンドを更新する |
-- 引数 | 起動のたびに先頭へ渡す固定引数 |
toolのような短い名前は登録所で探します。同じ名前のパッケージが2つ以上あるときは、候補を並べてどれにするか尋ねます。@scope/toolと書けば尋ねません。main(args)を持つスクリプトです。公開パッケージはmod.gd、ローカルのディレクトリはgd.jsonのmainを使います。--allow-*と--mountは、起動のたびに同じ設定で使われます。--rootを付けて導入したコマンドは、同じ--rootを付けて削除します。@importはconst 名 = preload(...)の短い書き方です。
外部依存がなくても使えます。実際の登録所の依存とロックファイルを含むsamples/packagesを用意しています。
@import greet
@import "./util"
@import greet/style as theme
gd.jsonのimportsに宣言した呼び名だけを解決します。同名のファイルを探しに行きません。./または../から書きます。 .gdは省略できます。同名のファイルとディレクトリが両方あるときは"./util.gd"のように指定します。asが無ければ最後の要素そのままで、mod.gdを持つディレクトリはディレクトリ名です。gd fmtは@importをそのまま残します。@importを知らないので、Godotと共有するファイルではconstとpreloadを書いてください。パッケージはgd.jsonを根に持つ一つのプロジェクトです。gd init @scope/nameがmod.gdとテストのテンプレートを作り、 gd testで回し、gd publishで公開します。
{"name":"@scope/hello","version":"1.0.0","main":"src/mod.gd","include":["src"]}
パッケージの本体は、作者のGitHub Releaseから配ります。登録所が持つのは、ファイルの場所と指紋(SHA-256)だけです。
gd publish # Write the release files to tmp/release/scope-hello-1.0.0/.
gh release create 1.0.0 tmp/release/scope-hello-1.0.0/*
gd publish https://github.com/OWNER/REPO/releases/download/1.0.0
gd add hello gd:@scope/hello@^1.0.0
1. 引数なしのgd publishは、公開するファイルをtmp/release/<scope>-<name>-<版>/へ書き出します。ファイル名は中身のSHA-256です。 2. それらをGitHub Releaseのアセットとして上げます。同じReleaseに複数のパッケージや版のファイルを置いても、名前は衝突しません。 3. ReleaseのダウンロードURLを付けてgd publishを実行します。gdはURLから各ファイルを取得し、手元と一致することを確かめてから登録所へ登録します。
公式の登録所へ投稿したパッケージは、審査で承認されると検索・インストールできます。gd publishが審査番号を表示した場合は、承認されるまで公開されません。承認の直前にも、登録所がReleaseのファイルを照合します。
mod.gdです。複数ファイルならincludeへファイルまたはディレクトリを明示します。gd.jsonのimportsで他の登録所パッケージを使えます。gd publishがそのimportsを登録所へ載せます。class_nameは公開できます。installは同名クラスの衝突を検査し、衝突すれば全体を元へ戻します。gd.jsonのgodotをtrueにすると、gd固有のAPIを使わず本家Godotでも動くという作者の宣言になり、gd searchが[godot]と示します。開発中のパッケージはgd add ../pathでローカルから足します。呼び名は先のgd.jsonのnameから取ります。 チェックアウトをpkg/<呼び名>/へ複製し、内容を比較するハッシュ値が変われば次の実行で複製し直します。 .で始まるファイル、pkg/、tmp/、gd.jsonを持つ下位ディレクトリ、tokenは複製しません。 gd publishは、ローカル importの先にnameとversionのあるgd.jsonがあれば登録所の範囲に変換し、無ければ拒みます。
リポジトリで、実際の登録所をループバックで起動できます。登録所の情報はtmp/dev-channel/dataへ保存されます。
export GD_TOKEN='開発用のトークン'
uv run --no-project python -B devtools/channel.py serve --scope dev --port 8787
別のターミナルでGD_REGISTRY=http://127.0.0.1:8787と同じGD_TOKENを設定し、@dev/nameのパッケージからgd publish --dry-run、gd publishを実行します。書き出したファイルは、python3 -m http.server 8788 --bind 127.0.0.1 --directory tmp/releaseなどでループバックから配り、gd publish http://127.0.0.1:8788/dev-name-1.0.0で登録します。開発用の登録所に限り、ループバックのHTTPを受け付けます。利用側もGD_REGISTRYを設定すれば、gd search、gd add、gd install、gd install -g、gd compileがその登録所を使います。プロジェクトのgd.jsonにregistryがある場合は、そのURLが優先します。
gd installは依存グラフ全体を解決します。版は、gd.lockが固定した版、今回すでに選んだ版のうち範囲を満たすもの、 登録所の最新一致の順で選びます。
gd.lockは解決したimportsの設定も保持します。設定が変わった実行では同じ依存関係の解決処理で再解決し、要求外の古い版を使いません。 --frozenは設定の不一致を拒否します。同じパッケージに複数の別名がある場合、辞書順で最初の別名を配置先に使います。
pkg://@scope/name@版/です。pkg://<呼び名>/は、書いたスクリプトが属するパッケージのimportsで正式パスへ展開されます。同じ呼び名でもパッケージごとに違う版を指せ、同じ版はどこから辿っても一つのスクリプトです。gd.lockには各パッケージのimportsの解決先も記録され、gd infoが一覧します。gd uninstallとgd updateは、どのパッケージも使わなくなったものをgd.lockとpkg/から外します。本家Godotなどres://しか読めない環境と共有するときは、gd.jsonへ"place": "project"を書きます。 パッケージをpkg/<呼び名>/へ複製し、pkg://もres://pkg/もそこを指します。 他のパッケージだけが使うものはpkg/@scope/name@版/へ置きます。
gd install --godotは、パッケージをaddons/<呼び名>/へ複製します。add、update、uninstall、infoでも--godotを指定します。パッケージ内にaddons/があっても、その部分だけを取り出すことはありません。project.godotのあるディレクトリではplaceの既定がprojectになり、.gitignoreは書きません。gdの無い同僚が開けるようpkg/をコミットします。preload、load、extendsに書かれたres://参照を配置先へ書き換えます。文字列、コメント、実行時に組み立てるパスは書き換えません。placeはファイルの置き場を決めるだけで、gd固有のAPIや構文をGodot向けに変換する機能ではありません。共有するソースは標準構文と相対preloadで書きます。placeに関わらずpkg/<呼び名>/へ置きます。ext:で取り込んだ拡張のクラスだけです。プロジェクトのスクリプトならgd.json、パッケージのスクリプトならそのパッケージのimportsが基準です。[classes]に無いクラスを登録すると起動時に止まります。gd compileを配布先のOSで実行してください。gd.jsonの設定は次の11件です。
| 名前 | gd initの生成値 / 未指定時 | 意味 |
|---|---|---|
name | my-tool / 必須 | プロジェクト名。publishは@scope/nameが必要 |
version | 0.1.0 / 必須 | パッケージのバージョン |
tasks | run/testの2件 / 無し | gd taskから呼ぶコマンド |
imports | {} / {} | 呼び名と依存先。publishするパッケージでは登録所パッケージだけ |
registry | 未指定 / 環境または公開登録所 | プロジェクト固定の登録所URL |
main | 未指定 / mod.gd | publishするmod.gdまたは.gdextension入口 |
include | 未指定 / mainだけ | GDScriptだけで書かれたパッケージへ含めるmain ディレクトリ内のファイルまたはディレクトリ |
place | 未指定 / cache(project.godotがあればproject) | パッケージの置き場。projectでpkg/へ複製する |
godot | 未指定 / false | gd固有のAPIを使わず本家Godotでも動くパッケージの宣言 |
description | 未指定 / 空 | 登録所に出す説明 |
assets | 未指定 / 無し | Godotアセットの管理用の呼び名とチャンネル:作者/名前[@版]。addons/へ配置する |
gdが読む環境変数は次の通りです。スクリプトから環境を読む実行では--allow-envで名前を許可します。
| 環境変数 | 用途 |
|---|---|
GD_CACHE_HOME | パッケージのキャッシュ根。未指定はWindowsのLocalAppData内gd。macOS/Linuxは絶対パスのXDG_CACHE_HOME/gd、それがなければホームディレクトリ内.gd。HOME未設定時はOSの利用者情報を使う |
GD_INSTALL_ROOT | gd install -gで入れるコマンドの置き場。--rootが優先 |
GD_USER_HOME | user://の保存先。絶対パスを指定する。未指定ではOSの利用者データ領域(macOSは~/Library/Application Support/gd/user、Linuxは~/.local/share/gd/user、Windowsは%APPDATA%/gd/user)に、実行したスクリプトのディレクトリごとに作る |
GD_REGISTRY | 登録所。未指定はhttps://gd.progsha.com/pkg。gd.jsonのregistryが優先 |
GD_RELEASES | gd upgradeが読む配布元。未指定はhttps://github.com/prog-sha/gd/releases |
GD_TOKEN | publishのトークン。設定ファイルへ書かず、publishするプロセスだけへ渡す |
LC_ALL、LANG | gd docの手引きの言語 |
GD_WORKER | --workersが作る内部印。利用者が設定する値ではない |
遠隔パッケージと登録所はHTTPSを使います。ループバックの開発用登録所に限りHTTPも使えます。 取得したパッケージとネイティブライブラリは登録所索引のSHA-256と照合します。 パッケージの全ファイル合計は500 MiBまでです。
compileで、スクリプト、HTMLテンプレート、静的ファイル、マイグレーション、依存パッケージ、対象OSのGDExtensionを1つの実行ファイルへまとめます。配布先にキャッシュは要りません。
gd compile -o app main.gd
./app
gd.jsonが名指すパッケージと、それらが取り込むパッケージを全部同梱します。./app serve --no-scene-tree --allow-netで常駐できます。.envなど.で始まるファイルとgd.jsonのtokenを除きます。.envを除外しますが、ソースに書いた値は実行ファイルに残ります。gd searchはパッケージに加え、Godotの公開アセットカタログとgdの審査済みカタログを検索します。独自の登録所を設定している場合は、その登録所だけを検索します。
| チャンネル | 用途 |
|---|---|
official | Godot Asset Storeのアセット |
gd | gdの審査済みアセット |
検索結果のasset:チャンネル:作者/名前を、そのままgd addに渡します。
gd search dialog
gd add asset:official:publisher/dialog
gd add ui asset:gd:publisher/dialog@1.2.0
gd install --frozen --cached-only
gd update ui
gd uninstall ui
asset:official:publisher/dialog@#123のように指定します。名前に空白を含む場合は引数全体を引用符で囲みます。officialになります。取得に失敗しても別のチャンネルへ切り替えません。gd.jsonのassetsに依存先を記録し、gd.lockに取得元・選んだ版・SHA-256を固定します。両方をコミットしてください。asset:で指定するGodotアセットは、ZIP内のaddons/以下をプロジェクトのaddons/へ配置します。assetsの呼び名は管理用です。通常のパッケージはimportsに記録し、@importで読み込みます。@1.2.0のように指定した版はupdateでも変わりません。--frozenではロックを変更せず、--cached-onlyでは通信しません。キャッシュのない版をオフラインで取得することはできません。アセットの詳細や版の一覧を調べるには、ソース配布に含むクライアントも使えます。
gd tools/store.gd channels
gd tools/store.gd search official 4.7 dialog
gd tools/store.gd show gd publisher dialog
gd tools/store.gd releases gd publisher dialog
gdはAPIが固まる前の公開版です。後方互換は前提にしないでください。変更した点と基準にしたGodotの版は CHANGELOGに書きます。 gdはGodot FoundationまたはGodot Engine プロジェクトの公式製品ではありません。
不具合はIssuesへ、公開すべきでない脆弱性は GitHubの非公開報告から知らせてください。
ここにある機能は開発中です。使い方や仕様は予告なく変わります。参考程度にご覧ください。
gd editorでエディタを開きます。初回は画面用の実行ファイルgd-godotを自動で導入します。
| やりたいこと | コマンド |
|---|---|
| エディタを開く | gd editor |
| プロジェクトを指定して開く | gd editor <プロジェクトディレクトリ> |
| プロジェクトを画面付きで実行する | gd run-game <プロジェクトディレクトリ> |
詳しくはgd-godot マニュアルを参照してください。
GD.online.match()は、オンラインゲームの対戦相手を探すサーバーを作ります。部屋は自分のアドレスと人数を知らせ、 参加する側は空きのある部屋を1つ受け取ります。状態はプロセスのメモリ、または複数のプロセスで共有するキー値サーバーに置きます。 変数に@onlineを付けてサーバーとクライアントで状態を同期する仕組みも準備中です。
English | 日本語
gd is a single command for writing command-line tools, websites, Web APIs, scheduled jobs, and data processing in GDScript. It is Godot built small without a display, and it runs a single .gd file without a project.godot.
You start the way you would with a Python or Node.js script. When you need them, type checking, tests, packages, databases, a Web server, and a standalone executable are available in the same GDScript. For game screens and rendering, use upstream Godot.
Together with Godot itself, apps, frontends, servers, and CLI tools can all be written in one language, GDScript. The same script runs on macOS, Linux, and Windows, and waits on networking and databases do not stop other work. It links directly with C++ through GDExtension.
Speed matters too. gd supports HTTP/2, other work proceeds while a connection waits, and text and JSON processing is fast.
Prebuilt downloads are available for macOS arm64/x86_64, Linux x86_64, and Windows x86_64. Linux arm64 can be built from source. You can also download an archive from Releases and put gd on your PATH.
curl -fsSL https://gd.progsha.com/install.sh | sh
Installs to ~/.local/bin. If the directory is missing from PATH, a y/N prompt offers to save it in your shell settings. Choose y, then open a new terminal to use it. Linux downloads require x86_64 and glibc 2.38 or newer.
Invoke-WebRequest -UseBasicParsing https://gd.progsha.com/install.ps1 -OutFile install-gd.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\install-gd.ps1
If the installation directory is missing from PATH, a y/N prompt offers to add it to your user PATH.
brew tap prog-sha/gd https://github.com/prog-sha/gd
brew install prog-sha/gd/gd
Use an apt-based distribution with glibc 2.38 or newer, such as Ubuntu 24.04 or Debian 13.
sudo install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://gd.progsha.com/apt/gd.asc | sudo tee /etc/apt/keyrings/gd.asc >/dev/null
sudo chmod 0644 /etc/apt/keyrings/gd.asc
echo 'deb [arch=amd64 signed-by=/etc/apt/keyrings/gd.asc] https://gd.progsha.com/apt stable main' | sudo tee /etc/apt/sources.list.d/gd.list
sudo apt update
sudo apt install gd
gd upgrade # Move to the latest release.
gd upgrade 0.8.0 # Move to a chosen version.
gd upgrade --dry-run # Show the version without installing it.
The download is checked against the release's SHA-256 before the running gd is replaced. A gd installed through Homebrew or apt is upgraded with brew upgrade gd or apt upgrade gd instead.
Install Python, uv, SCons, and a C/C++ compiler. Executables are written to bin/.
git clone --branch master https://github.com/prog-sha/gd.git
cd gd
scons platform=macos target=template_release -j8
# Linux ARM64: platform=linuxbsd arch=arm64
# Linux x86-64: platform=linuxbsd arch=x86_64
# Windows: platform=windows arch=x86_64 use_mingw=yes windows_subsystem=console
Create one file, hello.gd. No config file or package is needed. main() is the entry point, and the integer it returns becomes the process exit code.
func main():
print("Hello, world")
return 0
gd hello.gd
To check types and syntax without running, use check.
gd check hello.gd
Use @import "./settings" for a local file and @import hello for an installed package. Use the imported name directly; .gd and as settings can be omitted.
Put shared values in settings.gd:
const TITLE = "Hello"
const USER = "world"
Use them from main.gd:
@import "./settings"
func main():
print(settings.TITLE, ", ", settings.USER, "!")
return 0
This prints Hello, world!. Use this pattern when values need to be shared.
as only when a name conflicts.GD.web need no import.See Packages and distribution for installation and version locking.
The standard API has one entry point, GD, with a child per purpose. Scripts write these names as they are.
| What you want | Entry | Example |
|---|---|---|
| Files, text, time, HTTP client, async | GD | GD.file.read_text("a.txt") |
| Websites and Web APIs | GD.web | GD.web.app() |
| SQLite or PostgreSQL | GD.database | GD.database.client() |
| Redis | GD.database.redis | GD.database.redis.client() |
| TCP, UDP, TLS | GD.net | GD.net.listen_tcp("127.0.0.1", 8080) |
| Mail parsing and SMTP submission | GD.mail | GD.mail.parse_address("me@example.com") |
GD.database.postgres and GD.database.redis are advanced entries for features specific to one backend.
gd --help lists the commands, and gd install --help describes one command's arguments and options.
Pass the same spelling you write in a script to gd doc. Signatures come from the executable, so they match the implementation.
gd doc # short guide and entry points
gd doc manual # the full manual
gd doc GD # the children of GD
gd doc GD.file # file API
gd doc GD.http.fetch # the returned HTTP response
gd doc GD.web.app # Web application
gd doc SceneTree # Inspect a public engine class.
gd doc all # every public class
Return types such as Err and GDWebRequest are looked up by name alone. For Godot classes such as Node, SceneTree, and Timer, see the Godot class reference as well. The manual is shown in Japanese when LC_ALL or LANG starts with ja, and in English otherwise. The web version at gd.progsha.com switches between Japanese and English.
The examples avoid repeating type names. Variables assigned with := infer their types from the right-hand side. Parameters without annotations remain dynamic. Add annotations only where you want to fix a type boundary.
Arguments placed after the script name arrive in main(argv). An argument that could be mistaken for gd's own flag, such as --name=gd, reaches the script when placed after --.
func main(argv):
for arg in argv:
print(arg)
return 0
gd main.gd apple orange
gd main.gd -- --name=gd
To interpret them as flags, use GD.cli.flags(). It accepts --name gd, --name=gd, and -name=gd alike.
func main(argv):
var flags := GD.cli.flags()
flags.flag_str("name", "world", "who to greet")
var _parsed, parse_err := flags.parse(argv)
if parse_err:
print(flags.usage())
return 1
print("Hello, " + flags.get_str("name"))
return 0
Call external tools with GD.cli.run(). Only the calling GDScript waits, so other requests proceed even when it is called from a gd serve handler. Under --strict it needs --allow-run. You can narrow the target, as in --allow-run=/usr/bin/git.
func main():
var got, err := await GD.cli.run("git", ["rev-parse", "HEAD"])
if err:
return 1
print("code=", got["code"], " out=", got["output"])
return 0
A nonzero child exit returns an Err. Read the exit code from value.code and the output from value.output. A timeout or cancellation keeps the output captured so far.
The third argument, opts, changes the behavior.
| Name | Default | Meaning |
|---|---|---|
timeout | 0 | Seconds before giving up. 0 is unlimited. Past it, the child is shut down and Err.TIMED_OUT is returned |
output | true | Collect the output. With false, the child uses the parent's standard I/O directly and nothing is collected |
A function that can fail returns two values: a value and an Err. Receive both with var value, e :=. Their types come from the function declaration; a non-null e means failure. Assign them to existing variables with value, e = call(). Variables declared without types remain Variant; declare var value: T and var e: Err when you want static checks.
func main():
var text, e := GD.file.read_text("note.txt")
if e:
print(e.text())
return 1
print(text)
return 0
Append ? to a call to return its value and Err to the caller on failure. On success, use the value alone. A function using ? returns a value and Err. Without a return annotation, its first result is inferred from its return values; you can specify it as -> String, Err. On success, return value omits the null second result.
func title(path) -> String, Err:
var text := GD.file.read_text(path)?
return text.strip_edges()
func main():
var text, e := title("note.txt")
if e:
print(e.note("read the title").text())
return 1
print(text)
return 0
A readable file can still be invalid for your application. Create an Err when the message is empty. Err("message", kind, details) takes a description, a kind such as Err.INVALID_DATA, and optional details. Save this as read_message.gd:
# Read a message and reject empty contents.
func read_message(path: String) -> String, Err:
var text := GD.file.read_text(path)?
if text.strip_edges().is_empty():
return "", Err("Message is empty", Err.INVALID_DATA, {"path": path})
return text, null
# Print the message or report the failure to the caller.
func main() -> int:
var text, err := read_message("message.txt")
if err != null:
printerr(err)
return 1
print(text)
return 0
printf 'Hello!\n' > message.txt
gd read_message.gd
printf '' > message.txt
gd read_message.gd
The first run prints Hello!. After emptying the file, the second run reports Message is empty and exits with status 1.
-> String, Err declares two return values: a string and an error.text, null on success and "", Err(...) on failure.var text, err := read_message(...) and checks err before using text.? returns that error as it is.Waiting methods in HTTP, databases, GD.net, files, and others are written as ordinary function calls. Only the calling GDScript waits; other networking and timers keep running.
func main():
var res := GD.http.fetch("https://example.com/")!
print(res.status)
return 0
To start several operations together, use the variants ending in _async with GD.async.all().
func main():
var got = await GD.async.all([
GD.http.fetch_async.bind("https://example.com/a"),
GD.http.fetch_async.bind("https://example.com/b"),
])
for result: Array in got:
var res: GDHTTPResponse = result[0]
var e: Err = result[1]
if e:
print(e.text())
return 1
print(res.status)
return 0
| Entry | Purpose |
|---|---|
name_async() | Start the operation and return a GDTask that keeps its result. await it later, even after other waits, for the same result as the regular name. cancel() stops it |
GD.async.all(list) | Run several operations together and return the results in the order given |
GD.async.spawn(fn) | Run a function in the background. It keeps running after main() returns |
GD.async.sleep(sec) | Wait the given number of seconds |
To wait for a single one, receive it in the same shape as the regular name: var value, e := await GD.http.fetch_async(url).
Started operations can also be received one after another. If second finishes while first is awaited, second keeps its result.
func main():
var first := GD.http.fetch_async("https://example.com/a")
var second := GD.http.fetch_async("https://example.com/b")
var a, a_err := await first
var b, b_err := await second
if a_err or b_err:
return 1
print(a.status, " ", b.status)
return 0
Keep three points in mind.
all() the GDTasks returned by _async(), or Callables made with .bind() as in the example above. Either way, a result that finishes early is not lost.spawn() does not move work to another thread. Use the _async variant when a standard module processes large data.main() or a function you wrote. A function passed to Array.map(), _init(), and member initializers cannot wait, so write a for loop or use GD.async.all().With what you have read so far, this builds a small API that accepts JSON and stores it in SQLite, in one script. The result is a development server with input validation and SQL parameter binding, started with narrowed permissions.
mkdir notes-api
cd notes-api
Save the following as main.gd.
# Store notes in an embedded database and expose a JSON API.
extends RefCounted
const PORT := 18080 # development port listening on loopback
const DB_PATH := "user://notes.sqlite3" # per-user writable area provided by gd
var app := GD.web.app()
var db := GD.database.client()
# Return notes as JSON, newest first.
func list_notes(req: GDWebRequest) -> GDWebResponse, Err:
var got, query_err := await GD.async.with_context_pair(req.context, db.query_async("SELECT id, title FROM notes ORDER BY id DESC"))
if query_err:
return query_err
return GD.web.json(got.rows)
# Store a validated title and return the created row.
func add_note(req: GDWebRequest) -> GDWebResponse, Err:
var body := req.valid("body")
var made, query_err := await GD.async.with_context_pair(req.context, db.query_async(
"INSERT INTO notes(title) VALUES($1) RETURNING id, title",
[body.title]
))
if query_err:
return query_err
return GD.web.json(made.rows[0], 201)
# Prepare the database and routes, then listen on loopback.
func main() -> int, Err:
db.open({"driver": "sqlite", "path": DB_PATH})?
db.query("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT NOT NULL)")?
app.route("GET", "/notes", list_notes)
app.route("POST", "/notes", add_note, [GD.web.json_body(GD.web.object_rule({
"title": GD.web.text_rule({"min": 1, "max": 120}),
}))])
app.listen(PORT, "127.0.0.1")?
print("listening on http://127.0.0.1:%d" % PORT)
return 0
Read it from the top.
app is the router and db is the database connection. Both are script variables so the server can keep running after main() returns.main() first opens SQLite and creates the table. user:// in DB_PATH is a per-user writable area provided by gd.app.route() registers an HTTP method, a path, and the function to call for it (the handler).GDWebRequest and builds the reply with GD.web.json(). A ? in the middle returns the failure to the server, which becomes a status such as 500.GD.web.json_body(). The handler is called only when the body matches the rule, and the value that passed arrives in req.valid("body").$1. SQL is never built by string concatenation.Run unverified scripts and servers exposed to the outside with --strict, which denies permissions by default. Here the listener is limited to one loopback port. serve keeps the process alive after main() returns, and it is the command to use for servers.
gd check main.gd
gd --strict --allow-net=127.0.0.1:18080 serve main.gd
curl -s -X POST http://127.0.0.1:18080/notes \
-H 'Content-Type: application/json' \
-d '{"title":"try gd"}'
curl -s http://127.0.0.1:18080/notes
The first call returns status 201 with the created row, the second the stored array. An empty title, a title over 120 characters, or a non-JSON body is rejected with 400. Press Ctrl-C in the terminal that started it to stop.
In production, keep this process on loopback behind a TLS reverse proxy, and switch storage that must survive crashes to PostgreSQL. Keep connection details out of the source and read them from allowed environment variables.
Start with normal execution. --strict is an advanced mode for explicitly designing and configuring the permissions a script needs.
| Mode | Suited to | Restrictions |
|---|---|---|
| Normal execution | Running trusted source during development | Neither files nor the network are restricted |
--strict | Unverified scripts, public servers | The startup directory is read-only; absolute paths outside it are denied. Network, environment variables, child processes, native extensions, and system information are denied by default |
Under --strict, start by listing what the script uses.
gd --strict \
--mount store=/srv/app:rw \
--allow-net=db.example.com:5432 \
--allow-env=DATABASE_URL \
main.gd
| Flag | Grants |
|---|---|
--mount name=path:r / --mount name=path:rw | Read or read/write on a named directory |
--allow-net=host:port,... | Connecting and listening. Without a value, everything |
--allow-env=name,... | Environment variables |
--allow-run=command,... | Child processes |
--allow-ext=path,... | Native extensions a script loads while running |
--allow-sys=item,... | Machine and system information |
--deny-* | A denial that wins over the matching allow |
-A | Allow everything except files. For temporary use during development |
--strict applies to the commands that run a script: run, serve, test, task, eval, and repl. Commands that do not run a script, such as check, fmt, and package operations, are unaffected.
A script sees files through four kinds of location. Write the name of the location at the start of the path, or write an absolute path as it is.
| Spelling | Location | Under strict |
|---|---|---|
res://a.txt | The directory the script was started from | Read-only |
user://a.txt | Writable area gd keeps for each script in the user's data folder. It survives restarts | Read/write |
store://a.txt | The name given by --mount store=/srv/app:rw | As specified |
/etc/hosts | That location on the machine | Denied unless it is inside the startup directory |
When in doubt, put files you only read under res:// and files you save under user://.
--mount. -A does not widen file access.-, such as store or uploads. These names are used by gd and cannot be chosen: res, user, uid, pipe, local, libgodot, tcp, unix, http, https, file, data, cache, pkg, and global.--mount or absolute paths. Put files under res:// or user:// there.--allow-net, localhost:8080 also covers IPv4 loopback 127.0.0.0/8 and IPv6 ::1 on the same port.*.example.com:443 allows its subdomains.gd serve is the resident way to run, and it creates no SceneTree. Networking, timers, await, custom Signals, GD.async.sleep(), and queue_free() on nodes outside a tree all work. With no work to do, it sleeps until the next deadline or network notification, so there is no cycle to tune.
| What you want | How |
|---|---|
| Keep a Web server or scheduled job resident | gd serve main.gd |
Use Node _process(), _physics_process(), process_frame, SceneTreeTimer, or high-level multiplayer | Normal execution without serve |
| Run a script extending SceneTree or MainLoop | Normal execution without serve |
| Check during development that no SceneTree slips in | gd --no-scene-tree --allow-net serve app.gd |
| Listen with several processes | --workers=<n> or --workers=auto. n is an integer of 1 or more |
Under serve, a script that only extends Node is not added to a tree. --no-scene-tree reports a diagnostic as soon as a SceneTree is created and exits with code 1. It is inherited by --watch and --workers children.
Use GD.net for low-level networking. Godot's low-level types remain for compatibility, but new code should use GD.net.
func echo() -> int, Err:
var listener := GD.net.listen_tcp("127.0.0.1", 8080)?
var conn := listener.accept()?
var data := conn.read(65536)?
conn.write(data)?
conn.close()
return 0
GDTCPConn keeps reads and writes in separate queues, so several GDScripts may call it concurrently.close(), waiting reads and writes end with Err.INTERRUPTED. A listener waiting to accept does the same.timeout is never extended.Open TLS with GD.net.dial_tls(host, port, opts). It verifies the certificate chain and host name by default, and a failure never falls back to plaintext. The result is the same GDTCPConn used for TCP.
opts | Meaning |
|---|---|
timeout | One deadline in seconds covering both connect and handshake |
ca_file | A private CA. It takes precedence over the environment settings |
cert_file, key_file | Client authentication. Provide both, as files inside permitted mounts |
server_name | Check the certificate against a name different from the dial address |
next_protos | An array of ALPN names. One name is 1–255 bytes, and the whole list is up to 65535 bytes |
insecure_skip_verify | Skip verification. Use only for tests where verification is deliberately unnecessary |
Read the negotiated result from negotiated_protocol and version in connection_state(). TLS 1.2 is 771 and TLS 1.3 is 772.
Without other settings, the trusted CAs are the OS trust settings on macOS and Windows, and the system CA bundle on Linux. Set SSL_CERT_FILE or SSL_CERT_DIR before starting the process to use the given CAs on any OS. Directory lists use : on Unix and ; on Windows.
When a server requires client certificates, pass client_ca (a trusted CA bundle) and client_auth in the opts of app.listen_tls(port, cert, key, host, opts). A missing client_ca uses the system trust settings.
client_auth | Behavior |
|---|---|
none | Does not request a certificate |
request | A certificate is optional. It is not verified |
require | A certificate must be presented. It is not verified |
verify_if_given | Verifies a certificate only when one is presented |
require_and_verify | Requires a verified certificate |
Open UDP with GD.net.listen_udp(). A received packet carries the sender's host and port, so you can reply to it directly.
func echo_udp() -> int, Err:
var conn := GD.net.listen_udp("127.0.0.1", 9000)?
var packet := conn.read_from()?
conn.write_to(packet.data, packet.host, packet.port)?
conn.close()
return 0
write_to() an IP address. Turn a host name into one first with GD.net.resolve(name)?.read_from() returns one packet. Bytes beyond the requested size are dropped and packet.truncated becomes true.GD.net.local_addresses() lists this machine's addresses.GD.mail parses addresses and headers and sends mail through an SMTP server.
send_mail the whole message, headers and body, as bytes.--strict, the server needs --allow-net.func main() -> int, Err:
var message := "From: me@example.com\r\nTo: you@example.com\r\nSubject: Hello\r\n\r\nHello\r\n".to_utf8_buffer()
GD.mail.send_mail("smtp.example.com", 587, "me@example.com", PackedStringArray(["you@example.com"]), message, {
"tls": "starttls", "timeout": 10.0,
"auth": GD.mail.plain_auth("me@example.com", "secret"),
})?
return 0
GD.file reads and writes files and handles paths. The directory you started from is res://, and absolute paths work as written. To write to an outside directory under strict, write the name given by --mount store=/srv/app:rw as in store://users.csv.
func main() -> int, Err:
var rows := GD.data.csv_objects(GD.file.read_text("store://users.csv")?)?
GD.file.write_text("store://users.json", JSON.stringify(rows))?
return 0
File operations suspend only the calling GDScript, even under their regular names. Other requests proceed while a Web server handler reads a file. Use the variants ending in _async only to start several operations together.
func handler(_req) -> GDWebResponse:
var body, read_err := GD.file.read_text("store://big.json")
if read_err:
return GD.web.text("cannot read", 500)
return GD.web.text(body)
Files embedded by compile can be read, listed, and served statically through the same API.
To read without holding the whole file in memory, open a GDFileStream with GD.file.open(path, mode). Modes are read, write, append, and read_write. Call close() when done.
| Method | Behavior |
|---|---|
read(max) | Returns up to max bytes. It may return fewer. An empty successful value is EOF |
write(bytes) | Writes all bytes and returns the count. On a failure partway, the first result retains the number already written |
Operations on one stream run in arrival order, and separate streams proceed in parallel. Append always writes at the end, even after a seek. read_bytes() also retains the bytes already read in the first result when it fails partway. read_text() rejects input too large for a String instead of truncating it, so handle large files as bytes or a stream.
When several processes update the same file, use GD.file.replace_text(path, old, body). It replaces the content only when the old you read still matches the current content, so a concurrent edit is never silently overwritten. Pass null as old to create a new file.
| Purpose | Entry |
|---|---|
Reading CSV, TOML, YAML, JSONL, JSONC, XML, INI, TAR, front matter, and .env files | GD.file.read_csv(path) and similar |
| In-memory conversion of the same formats, JSON, codecs, hashes, HMAC, PBKDF2, HKDF, byte sequences | GD.data |
| UUID and ULID | GD.id |
| Time conversion and arithmetic | GD.time |
| Text formatting and comparison | GD.text |
| HTML entities, tags, and gdhtml (a micro template with Mustache syntax) | GD.html |
| Flags and environment variables | GD.cli |
| Array and dictionary operations | GD.collection |
| Special math values and bit operations | GD.math |
| Version comparison | GD.version |
| Logging to the terminal and files | GD.log |
| Test assertions | GD.test |
Environment variables and .env have separate entries by what you read.
| What you read | Entry |
|---|---|
| Process environment variables | GD.cli.env(name, fallback) and GD.cli.require_env(name). Strict mode needs --allow-env |
A .env file | GD.file.read_env(path). Reads the file into a dictionary |
| A dotenv string | GD.data.env(src) and GD.data.to_env(data). Convert to and from a dictionary in memory |
In-memory conversions compute in place under their regular names, and their _async variants compute on another thread. Use _async for large inputs. Run gd doc GD.file and gd doc GD.data for the exact lists. Checks and limits per format are in the description of each entry in the API reference.
GD.collection operations that take a Callable yield to other work about every 1 ms. Each GD.log call waits until the write completes and never truncates the message. Check failures through the second Err result; GD.log.flush() waits for all earlier output.
Use GD.data.json_encode(value) to produce JSON bytes and GD.data.json_decode(bytes) to read received bytes. GDWebRequest.json(), GDHTTPResponse.json(), and each JSONL line follow the same rules.
func main() -> int, Err:
var bytes := GD.data.json_encode({"id": 1, "tags": ["a", "b"]})?
var value := GD.data.json_decode(bytes)?
print(value.id)
return 0
int. Fractions and exponents become float.{"deterministic": true} when the same value must always give the same bytes, as for signatures or cache keys.GD.data returns SHA-1, SHA-224/256/384/512, and SHA3-224/256/384/512 digests. HMAC, PBKDF2, and HKDF accept sha1, sha224, sha256, sha384, sha512, sha3-224, sha3-256, sha3-384, or sha3-512 as the hash name. PBKDF2 and HKDF accept an output length and return an Err for an invalid hash or settings outside the supported range. PBKDF2 iteration counts of one or less perform one iteration.
Create main.gd and index.html in the same directory. One route renders a greeting through an HTML template; another returns the same data as JSON.
main.gd:
# Serve a greeting as an HTML page and a JSON response.
var app := GD.web.app()
# Build the shared response data from the requested name.
func greeting(req: GDWebRequest) -> Dictionary, Err:
var name := req.query.get("name", "world")
if not name is String:
return {}, Err("name must be text", Err.INVALID_DATA)
return {"name": name, "message": "Hello, " + name + "!"}
# Render the page with escaped template values.
func home(req: GDWebRequest) -> GDWebResponse, Err:
return GD.web.view("index.html", greeting(req)?)
# Return the same data as JSON.
func hello(req: GDWebRequest) -> GDWebResponse, Err:
return GD.web.json(greeting(req)?)
# Listen locally, using an optional port argument.
func main(args):
var port := 8080 if args.is_empty() else int(args[0])
app.route("GET", "/", home)
app.route("GET", "/api/hello", hello)
app.listen(port, "127.0.0.1")!
print("http://127.0.0.1:", app.port())
return 0
index.html:
<!doctype html>
<!-- Display a greeting and let visitors choose the name. -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{message}}</title>
<style>
body { max-width: 36rem; margin: 4rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; line-height: 1.6; }
input, button { padding: .6rem; font: inherit; max-width: 100%; box-sizing: border-box; }
</style>
</head>
<body>
<h1>{{message}}</h1>
<form action="/" method="get">
<label>Your name <input name="name" value="{{name}}"></label>
<button type="submit">Say hello</button>
</form>
<p><a href="/api/hello?name={{name}}">View the JSON response</a></p>
</body>
</html>
Run from that directory:
gd serve main.gd
Open http://127.0.0.1:8080/?name=Alice to insert “Hello, Alice!” into {{message}}. /api/hello?name=Alice returns {"name":"Alice","message":"Hello, Alice!"}. Template values are escaped for their HTML context.
serve keeps listening after main() returns. Stop with Ctrl+C.
route(method, pattern, handler) binds an HTTP method and a path to a handler. :name in the pattern arrives in req.params["name"]. A HEAD request is answered by the GET route. A request whose path matches but whose method does not gets a 405. A handler receives a GDWebRequest. It reads only the needed body through req.read(), bytes(), text(), json(), or save(). A body sent by an HTML form becomes a dictionary with GD.http.decode_query(req.text()?).
The value a handler returns becomes the reply. Return one of the values in the table below as it is, such as return GD.web.json(data).
When a step fails, return its Err with call()?. The Err becomes the status code in the last row of the table. Register app.on_error(handler) to decide that reply yourself.
| Returned value | Reply |
|---|---|
GD.web.html(body), GD.web.view(path, data) | HTML |
GD.web.json(data) | JSON |
GD.web.text(body), GD.web.bytes(body, type) | Text, or any media type |
GD.web.stream(producer) | A body written a little at a time. See "Web operations and advanced features" |
GD.web.redirect(to) | 302. to is limited to a path on the same site. Set away to true to send elsewhere |
GD.web.not_found() | 404 |
| A string | 200 as text/plain |
A dictionary with body | A handwritten reply. status, type, and headers are optional |
A dictionary without body | 200 as JSON |
null | 204 |
An Err | Status by kind. INVALID_DATA → 400, UNAUTHENTICATED → 401, PERMISSION_DENIED → 403, NOT_FOUND → 404, LIMITED → 429, UNSUPPORTED → 501, TIMED_OUT → 504; other kinds → 500 (all are Err constants) |
A reply can be adjusted as follows.
GD.web.text("Not found", 404). bytes takes it after the media type.GD.web.header(reply, name, value) adds a header to a reply.GD.web.guard(reply) adds defensive headers such as Content-Security-Policy at once.app.show_errors(true).req.query is not always text. Check it with is String before use, as in the example above.req.path is the path with escapes such as %20 turned back into characters. req.target holds the text as it arrived.The router also accepts the following.
| Registration | Purpose |
|---|---|
app.static("/assets", "res://public") | Answer GET and HEAD under the prefix with files from the directory. The media type comes from the extension, and nothing outside the directory is served. Write the index of / as a route |
app.group("/api", [middleware]) | A route group with a shared prefix and middleware. The result has route() and use() |
app.fallback(handler) | Requests matching no route. Return the 404 page here |
app.on_error(handler) | The reply when a handler returns a failure |
app.after(handler) | Reshape the reply before sending. Receives func(req, reply) and returns it with headers added |
Middleware is a function called before the handler. It receives a GDWebRequest, returns null to continue, or returns a reply to stop there. An object with handle(req) also works. Pass values to later stages with req.keep(name, value) and read them with req.kept(name).
| Registration | Scope |
|---|---|
app.pre(mw) | Before route selection. Every request |
app.use(mw) | After route selection. Every route. Can read req.params |
group.use(mw) | Routes in that group |
app.route(method, pattern, handler, [mw]) | That route only |
Input validation is middleware too. GD.web.json_body(rule), GD.web.query(rule), and GD.web.params(rule) check the body, query, and path values, and put the values that pass into req.valid("body"), req.valid("query"), and req.valid("params"). Rules are built from GD.web.text_rule(), int_rule(), number_rule(), bool_rule(), list_rule(), and object_rule(), with GD.web.optional() and GD.web.one_of() for omission and choices. Query and path values are strings, so check them with text_rule() and convert with to_int() when needed.
var app := GD.web.app()
func show(req) -> GDWebResponse, Err:
var params := req.valid("params")
return GD.web.json({"id": params.id})
func main():
app.route("GET", "/posts/:id", show, [GD.web.params(GD.web.object_rule({"id": GD.web.text_rule({"min": 1, "max": 20})}))])
app.listen(8080)!
return 0
The built-in middleware are GD.web.sessions(), GD.web.csrf(), GD.web.jwt(), and GD.web.rate(). The authentication section uses them.
As pages grow, move the HTML into template files and render them with GD.web.view(path, data). The template language is gdhtml, a micro template with Mustache syntax. It handles {{name}}, {{{html}}}, #if, #unless, #each, #with, else, and {{> header}}. Using {{> header}} from views/page.html reads views/partials/header.html at the same level.
<!-- views/page.html -->
{{> header}}
<main><h1>{{title}}</h1></main>
<!-- views/partials/header.html -->
<header><a href="/">gd app</a></header>
func page(_req) -> GDWebResponse, Err:
return GD.web.view("views/page.html", {"title": "Top"})
Double-brace values are escaped by the context they appear in. The template author is trusted, the values inserted are not.
| Context | Handling |
|---|---|
| HTML body, quoted and unquoted attributes, attribute names | HTML escape |
href="{{url}}" | Relative URLs and http, https, mailto pass. data-href is treated the same |
href="/work/{{path}}", href="/?q={{query}}" | Paths are normalized keeping separators, query values are percent-escaped |
onclick, script body | Encoded as JSON in a form where </script> cannot break the structure, even for application/json |
style | Safe single CSS values and CSS strings and URLs pass |
| Dangerous URLs, srcset, CSS values, attribute names | Replaced with #ZgdunsafeZ or ZgdunsafeZ without failing the whole page |
{{{html}}} are the only unescaped entry, and they work only in the HTML body. Pass only fixed HTML or a sufficiently checked value.each iterations end in different contexts, an unclosed tag, or an ambiguous URL or JavaScript context fails to render.For a server that renders the same template repeatedly, parse it once at startup with GD.html.template(source, partials)?, then call execute(data)? on the returned value from each request. The parsed value is immutable and can be used by several requests at once. execute_bytes(data)? produces UTF-8 bytes directly, so they can be returned as is with GD.web.bytes(body, "text/html; charset=utf-8").
Login state is held by GD.web.sessions(). issue(value) creates a session ID, and the value of cookie(id) is returned as Set-Cookie. On routes that carry the same store as middleware, the value behind the cookie's ID arrives in req.kept("user"), and a missing session is a 401. An invalid middleware configuration returns null from its factory; passing it to app.use() or a route makes app.listen() report a configuration error.
var app := GD.web.app()
var sessions := GD.web.sessions()
func login(req: GDWebRequest) -> GDWebResponse, Err:
var form := GD.http.decode_query(req.text()?)?
var user := str(form.get("user", [""])[0])
if user.is_empty():
return GD.web.text("user is required", 400)
var reply := GD.web.redirect("/me")
return GD.web.header(reply, "Set-Cookie", sessions.cookie(sessions.issue(user)?))
func me(req) -> GDWebResponse, Err:
return GD.web.text("hello, " + str(req.kept("user")))
func main():
app.route("POST", "/login", login)
app.route("GET", "/me", me, [sessions])
app.listen(8080)!
return 0
cookie(id) sets Secure and HttpOnly. If the cookie does not arrive during development without TLS, use cookie(id, false). Log out with drop(id) and clear_cookie(). Sessions live in one process, so with several processes under --workers use JWT or an external store.
Attach GD.web.csrf() to write paths that authenticate with cookies. Requests other than GET, HEAD, and OPTIONS need the browser's Sec-Fetch-Site: same-origin. When old browsers or non-browser clients must be accepted, choose GD.web.csrf({"allow_missing": true}) and combine it with separate token verification.
var app := GD.web.app()
var sessions := GD.web.sessions()
func save_email(_r):
return "saved"
func main():
app.route("POST", "/account/email", save_email, [GD.web.csrf(), sessions])
app.listen(8080)!
return 0
When JWT is used as a login session, revoke issued tokens on password change and logout. check is called after the signature and standard claims are verified, and authentication passes only when it returns true. For example, put the user's ver in the token and increment the stored version on password change. With several workers, compare against something like a cache synced from a shared DB, not a per-process dictionary.
func token_auth(key, versions):
return GD.web.jwt(key, {"check": func(claims):
return versions.get(claims.get("sub", ""), -1) == claims.get("ver", -2)
})
To limit per IP behind a reverse proxy, list the proxy's IPs or CIDRs in trusted_proxies. gd strips trusted proxies from the right end of X-Forwarded-For and uses the first untrusted IP as the key. X-Forwarded-For is ignored when trusted_proxies is unset and when it comes from an untrusted peer, so a client cannot forge its own IP. IPv4 and IPv4-mapped IPv6 are matched as different things, so use an IPv6 CIDR to trust mapped addresses. Proxy settings with zones are rejected.
var per_ip := GD.web.rate({"limit": 60, "trusted_proxies": ["127.0.0.1", "172.18.0.0/16"]})
Allowed and 429 responses include X-RateLimit-Limit and X-RateLimit-Remaining. A 429 response also includes Retry-After in seconds.
Wait for shutdown with app.shutdown(context). It stops accepting new connections and keep-alive, then waits for in-flight requests. Past the deadline it returns Err.TIMED_OUT but does not kill in-flight requests. Use app.stop() when every connection must close immediately.
func close(app: GDWebApp):
var context := GD.async.context().with_timeout(10.0)
var _stopped, stop_err := app.shutdown(context)
if stop_err:
app.stop()
A handler can observe request completion and disconnection through req.context. with_cancel() and with_timeout() return a child context without changing the parent, and the parent's cancellation reaches the child. To cancel HTTP, database, process, and other two-result waits, wrap them with with_context_pair(), passing the context first. Use with_context() for single-value operations. The operation result is returned when it finishes first; when the context finishes first, the operation is canceled.
func load(req: GDWebRequest, db: GDDatabaseClient) -> Variant, Err:
return await GD.async.with_context_pair(req.context, db.query_async("SELECT * FROM posts"))
When handling large bodies or long handlers, set the limits explicitly with limits() before listening.
func main():
var limited_app := GD.web.app()
limited_app.limits({"header_bytes": 1048576, "header_values": 500, "header_timeout": 15.0, "body_timeout": 10.0, "job_timeout": 30.0, "jobs": 128})
return 0
To accept a 1 GB ZIP, put a per-request limit on it and stream it to a writable mount.
func main():
var app := GD.web.app()
app.limits({"body_timeout": 600.0})
app.route("POST", "/upload", func(req: GDWebRequest) -> GDWebResponse, Err:
req.limit(1000 * 1000 * 1000)?
req.save("uploads://package.zip")?
return GD.web.text("saved")
)
var _server, listen_err := app.listen(8080, "127.0.0.1")
return 0 if listen_err == null else 1
gd --strict --allow-net=127.0.0.1:8080 --mount=uploads=/srv/uploads:rw serve main.gd
How you read the body decides how much memory it uses.
| Reading | Memory use |
|---|---|
read(), save() | Read a little at a time. save() never holds the whole body in memory |
bytes(), text(), json() | Read the whole remaining body into memory. The body is kept after the first read, so every call returns the same content. Use save() for large bodies |
req.limit(bytes) | Body limit for that request. Past it, the reading operation fails |
req.limit() on a public server.header_bytes in limits().GD.web.stream(producer, length=-1, type="application/octet-stream", status=200) sends only what producer(writer) writes to the GDWebWriter. It never joins the whole body in memory. The producer may await, and it finishes by returning void or a value and Err.
GDWebWriter | Behavior |
|---|---|
write(data, offset=0, count=-1) | Sends a range of a byte array and returns the accepted bytes. When sending is backed up, it waits until it progresses |
write_text(text, offset=0, count=-1) | Sends a range of a string as UTF-8. Offset and count are in characters; the result is in bytes |
flush() | Waits for preceding writes to be sent. A disconnect shows up as an error here and as req.context cancellation |
length is the number of bytes to send. If the declared and actual lengths differ, the connection is closed. Unknown length (-1) uses DATA frames on HTTP/2, chunked framing on HTTP/1.1, and connection close as the end on HTTP/1.0.req.context cancellation.Start HTTPS with app.listen_tls(8443, "cert://chain.pem", "cert://key.pem", "127.0.0.1") and check the second Err result. Mount the certificate directory read-only with --mount cert=/path/to/certs:r. Pass a PEM chain and an unencrypted private key. When key validation fails, no port is opened.
TLS 1.2 and 1.3 are supported, and ALPN selects HTTP/2 or HTTP/1.1. Each HTTP/2 stream proceeds independently, and canceling one does not close the others. header_timeout also applies to an incomplete handshake. For requiring client certificates, see the TLS tables in "TCP and UDP".
GD.data.gzip_writer(writer, level=-1) creates a GDGzipWriter that gzips the bytes written to it and passes them to the writer below. The writer below can be a GDFileStream, a TCP connection, or a GDWebWriter. The whole body is never held in memory.
| Item | Details |
|---|---|
| Methods | write(bytes), flush(), close(), and reset(writer). Each returns a value and Err |
level | -2 (Huffman only), -1 (default), and 0..9 |
close() | Finishes the gzip trailer. It does not close the writer below |
reset(writer) | Clears errors and reuses the compressor at the same level |
header | name and comment (non-NUL Latin-1), extra (up to 65535 bytes), mod_time (Unix seconds from 0 to 4294967295), and os (default 255). Set it before the first write |
For HTTP, return GD.web.header(GD.web.stream(producer), "Content-Encoding", "gzip"); the producer creates the compressor, writes, and returns the result of close(). Checking Accept-Encoding and setting Vary are up to the caller. Do not compress secrets together with external input, and do not apply it to an already compressed body or a partial response.
For an IPv6-only localhost listener, use app.listen(8080, "::1")!. Under strict use --allow-net=[::1]:8080, and connect to http://[::1]:8080/. ::1 and 127.0.0.1 are separate listeners, and both differ from ::, which means every interface.
To let the OS pick a free port, read app.port() right after app.listen(0). The number is obtained while holding the listener, so no other process can take it. Check app.serve_error() for a listener failure after startup. Temporary resource shortages cause a short retry; a permanent failure closes the listener. Under strict the chosen port cannot be limited ahead of time, so allow the whole host, as in --allow-net=127.0.0.1. GD.net.free_port() and is_free() are momentary diagnostics, not a way to reserve that number.
The settings passed as a dictionary to GD.http.fetch() and the GD.web functions, with their defaults. Times are seconds and sizes are bytes.
| Entry | Setting and default | Meaning |
|---|---|---|
GD.http.fetch | method="GET", headers={}, body=null | HTTP method, request headers, request body |
| same | timeout=0.0, max_body=0 | Seconds for the whole request and bytes of the response body. 0 is unlimited. New TCP connections default to 30 seconds and TLS handshakes to 10 seconds |
| same | save="", sha256="" | Stream a 2xx body to save, returning an empty body. sha256 requires save, is 64 hex digits, and only a matching completed file is placed |
| same | authority="host:port" | Request target for CONNECT only |
GDWebApp.limits | jobs=0, job_timeout=0.0 | Number of async handlers kept and seconds. 0 is unlimited |
| same | header_timeout=0.0, body_timeout=0.0 | Seconds to finish receiving request header/body. 0 is unlimited |
| same | header_bytes=1048576, header_values=2147483647 | Header bytes including the request line, and the header line count |
GD.web.jwt_sign | ttl=900 | Seconds used to fill iat/exp. 0 does not add them |
GD.web.jwt / jwt_verify | leeway=0.0, require_exp=true | Clock tolerance in seconds, and whether exp is required |
| same | iss="", aud="", keep="jwt" | Issuer/audience match when non-empty, and the name kept on the request |
| same | check=Callable() | Revocation check receiving claims after signature verification. When set, only true passes |
GD.web.sessions | total=1024, per_user=3 | Sessions per process, and per user |
| same | idle=1800, life=43200 | Idle and maximum lifetime in seconds |
| same | cookie="sid", keep="user" | Cookie name and the name kept on the request. The cookie name uses ASCII token characters |
GD.web.rate | limit=60, window=60.0 | Largest burst per key, and the seconds that refill that many requests |
| same | expires=180.0 | Seconds after the last request before a key is released |
| same | keys=0, key=Callable() | Keys kept per process and the key selector. Zero is unlimited. A full explicit store evicts the earliest expiring key |
| same | trusted_proxies=PackedStringArray() | IPs or CIDRs of proxies whose forwarded IP is trusted |
GD.web.csrf | allow_missing=false | Whether to allow state changes from clients without Fetch Metadata |
GD.web.text_rule | min=0, max=4096 | Text length in characters |
GD.web.int_rule | min=-9223372036854775808, max=9223372036854775807 | 64-bit integer range |
GD.web.number_rule | min=-1e308, max=1e308 | Finite float range |
GD.web.list_rule | min=0, max=1024 | Element count |
GD.web.object_rule | extra=false | Whether to keep undeclared fields |
GDWebApp.limits accepts only the six listed setting names and rejects misspellings and body_limit.
A value outside the accepted range fails when set. The ranges are listed with each function in the API reference.
The client returned by GD.database.client() handles SQLite and PostgreSQL with the same code. Switching from the embedded SQLite in local development to PostgreSQL in production is done through the driver passed to open().
func main() -> int, Err:
var local := GD.cli.env("DB_DRIVER", "sqlite") == "sqlite"
var db := GD.database.client()
db.open({
"driver": "sqlite" if local else "postgres",
"path": "user://app.sqlite3",
"host": "127.0.0.1",
"database": "app",
"user": "app",
"password": GD.cli.env("PGPASSWORD", ""),
})?
db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")?
db.query("INSERT INTO users (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", [1, "ada"])?
var out := db.query("SELECT id, name FROM users WHERE id=$1", [1])?
print(out.rows[0].name)
db.close()
return 0
Table creation, INSERT, and SELECT all go through the one query(). It yields a dictionary with columns, rows, and tag, where rows is an array of dictionaries keyed by column name. In the example, out.rows[0].name is ada. SQL values are bound in order as $1, $2, and the spelling is the same on both drivers. SQL is not translated, so use SQL that works on both.
| Method | Purpose |
|---|---|
query(sql, args) | Collect and return the whole result |
query_row(sql, args) | Return only the first row. Err.NOT_FOUND when there is no row |
query_rows(sql, args) | Open GDDatabaseRows and read one row at a time. For large results |
stats() | Connection count, in use, idle, wait count, wait duration, and cumulative close counts by reason |
Advance query_rows() with while rows.next(). scan() returns a dictionary keyed by column name and values() returns an array in column order. After next() returns false, inspect err(). Call close() when stopping early.
func list_users(db: GDDatabaseClient) -> Variant, Err:
var rows := db.query_rows("SELECT id, name FROM users ORDER BY id")?
while rows.next():
var user := rows.scan()?
print(user.id, " ", user.name)
if rows.err() != null:
return null, rows.err()
return null
On a constraint violation, the second result e.info carries machine-readable details. violation is one of duplicate, not_null, or foreign_key, and columns lists the related column names. On PostgreSQL, code, table, and constraint are included when the server returns them. Values themselves are never kept in info. A failure reported by SQLite itself keeps source="sqlite" and its extended source_code. SQLite's foreign key message has no column names, so columns is empty there.
func save(db: GDDatabaseClient) -> void:
var _saved, e := db.query(
"INSERT INTO users(id,name) VALUES($1,$2)",
[1, "ada"])
if e and e.info.get("violation") == "duplicate":
var columns := e.info.get("columns", PackedStringArray())
print("duplicate columns: ", columns)
To make several updates one success or failure, use transaction(). The callback receives a GDDatabaseTx pinned to one connection. A null second result commits, while an Err rolls back.
func save(db: GDDatabaseClient, id: int, title: String) -> Variant, Err:
return db.transaction(func(tx: GDDatabaseTx) -> int, Err:
tx.query("INSERT INTO posts(id,title) VALUES($1,$2)", [id, title])?
tx.query("UPDATE counters SET value=value+1 WHERE name='posts'")?
return id
)
tx. The original db.query() is not part of this transaction.tx no longer accepts new SQL.When a PostgreSQL transaction fails because it collided with another one running at the same time (SQLSTATE 40001), serialize() retries it.
transaction() and is called in a new transaction on every attempt.func increment(db: GDDatabaseClient, id: int) -> int, Err:
var saved, e := db.serialize(func(tx: GDDatabaseTx) -> int, Err:
tx.query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")?
tx.query("UPDATE counters SET value=value+1 WHERE id=$1", [id])?
return id
)
return saved, e
To apply a schema in order, pass an array of statements to migrate() instead of splitting SQL on semicolons. If one statement fails, everything rolls back. On success it returns the number of statements applied. Versions and checksums are managed by the application.
func migrate(db):
return db.migrate([
"CREATE TABLE posts(id INTEGER PRIMARY KEY, title TEXT NOT NULL)",
"CREATE INDEX posts_title ON posts(title)",
])
| Item | SQLite | PostgreSQL |
|---|---|---|
| Suited to | Local development, a single process | Production, crash resilience, several workers |
| Connection | One per client. Journal and temporary tables live in memory | A pool that opens only the connections it needs. Set a maximum as in pool=25 |
| Extra entries | GD.database.sqlite.open() for short work done in place | GD.database.postgres for batched sends, arrays, and JSONB |
| Notes | Persistent databases recover unfinished writes with a rollback journal. Checkpoint existing -wal and -shm files with regular SQLite before opening | Hosts other than loopback verify the TLS certificate and host name by default. Loopback defaults to no TLS |
open() on GD.database.postgres.client() and GD.database.redis.client() takes the target as arguments, in the form open(host, port, opts).
query() calls on one client run in arrival order. Separate clients proceed concurrently, while writes to the same database file follow SQLite locking. The GDSQLiteDB and GDSQLiteStatement returned by GD.database.sqlite.open() are a synchronous API that runs directly on the caller. Use them only for short work and never concurrently. Use GDDatabaseClient for concurrent work.
The pool opens connections as they are needed and takes them back after use. Normally you just call query() without thinking about connections. When none is free, queries wait in turn.
| Goal | How |
|---|---|
| Run several SQL statements as one unit | Use transaction() instead of sending BEGIN yourself |
| Send several SQL statements together | query_many, fetch_many, exec_many |
| Detect a duplicate insert | Err.ALREADY_EXISTS. Read the SQLSTATE in e.info.code for the exact cause |
| See whether there are enough connections | wait_count in stats() (times a query waited for a connection) |
| Pin the authentication method | auth="scram". auth="md5" is for older servers |
Column values arrive as these types.
| Column type | Received value |
|---|---|
real, double precision | float |
numeric | Text, so no digits are lost |
json, jsonb | Dictionaries and arrays. Integers stay int |
Arrays such as int[] and text[] | An Array of the same element type. Nulls and nesting are kept |
A query that is cancelled or times out closes its connection. The SQL on the server may not stop at once. The character encoding is UTF-8.
Use Redis through GD.database.redis.client(). Pass the command name and its arguments separately to query().
func main() -> int, Err:
var redis := GD.database.redis.client()
redis.open("127.0.0.1", 6379)?
redis.query("SET", ["greeting", "hello"])?
print(redis.query("GET", ["greeting"])?)
redis.close()
return 0
| Goal | How |
|---|---|
| Tell that a value is missing | GET returns Err.NOT_FOUND |
| Send several commands together | pipeline(cmds). Results come back as an Array in the order sent |
| Use it from many requests at once | GD.database.redis.pool(). Connections open on the first query() |
Use MULTI, WATCH, SELECT, or subscriptions | A dedicated GDRedisClient, not the pool |
| Set a deadline | timeout in open() (seconds) |
The TLS choice is the same as PostgreSQL.
The settings passed as a dictionary to open(), with their defaults.
| Entry | Setting and default | Meaning |
|---|---|---|
GDDatabaseClient.open | driver="postgres", path="" | Driver and SQLite path: user://, a name mounted writable with --mount, or :memory:. res:// also works without --strict |
| same | host="127.0.0.1", port=5432 | PostgreSQL target |
| same | pool=0 | PostgreSQL maximum connections. 0 is unlimited. Unused by SQLite |
| same | max_rows=0, max_bytes=0 | Rows and bytes per result collected by query(). 0 is unlimited. Not applied to query_rows() |
GDPostgresClient.open | user="postgres", database="postgres", password="" | Credentials and database name |
| same | connect_timeout=0.0, timeout=0 | Connect and query seconds. Waiting for a pool connection counts toward the query time. Zero has no deadline; set either deadline when needed |
| same | auth="any", allow_cleartext_password=false | Pin the method with auth="scram"/"md5". A cleartext password reply only when explicit |
| same | tls=<decided by host>, ca="" | External hosts use verify-full, loopback disable. A CA file only when explicit |
GD.database.sqlite.open | busy_ms=0, max_ms=0, foreign_keys=false | Lock wait and execution deadline in milliseconds. busy_ms=0 reports contention immediately; max_ms=0 has no execution deadline. Enable foreign-key checks explicitly |
| same | max_rows=0, max_bytes=0 | Rows and bytes per result. 0 is unlimited |
GDRedisClient.open | password="", dial_timeout=5, read_timeout=5, write_timeout=5 | Password, and connect, read, and write deadlines in seconds. An explicit 0 is unlimited. timeout sets all three, and an individual setting wins |
| same | tls=<decided by host>, ca="" | The same TLS choice as PostgreSQL |
GD.database.postgres.pool | size default 0; 0 or 1..2147483647 | 0 is unlimited. Connections open only as needed |
GDPostgresPool.open | max_idle=2 | Connections kept after work ends. 0 keeps none. Never exceeds the maximum |
GD.database.redis.pool | size default 0; 0..2147483647 | Maximum connections. 0 selects ten times the CPU count. Simultaneous dials do not exceed the maximum |
GDRedisPool.open | pool_timeout=read_timeout+1.0 (30 seconds when the read deadline is 0), conn_max_idle_time=1800 | Deadline for waiting for a free connection, and how long a returned connection stays reusable. An explicit 0 is unlimited. An expired idle connection is closed at the next borrow |
Set read_timeout explicitly to extend the deadline for a long Redis query.
A query() over max_rows or max_bytes fails only that query. The whole connection is closed when ordering is lost through a deadline or a corrupt reply.
A value outside the accepted range fails when set. The ranges are listed with each function in the API reference.
A job that runs once at a fixed time is an ordinary script, called from the OS's cron or a systemd timer. gd needs no resident scheduler for it.
func collect() -> int, Err:
var now := GD.time.to_iso(GD.time.now())
GD.file.append_text("store://log.txt", now + "\n")?
return 0
func main() -> int, Err:
collect()?
return 0
gd --strict --mount store=/var/lib/app:rw collect.gd
A job that loops on its own interval is passed to GD.async.spawn() and kept resident with gd serve. Work passed to spawn() keeps running after main() returns.
func every(sec, fn):
while true:
await GD.async.sleep(sec)
fn.call()
func collect():
print(GD.time.to_iso(GD.time.now()))
func main():
var _job := GD.async.spawn(every.bind(60.0, collect))
return 0
gd serve schedule.gd
Stop it by ending the process. It is resident like a Web server, so serve is needed here too.
The core stays small. Features specific to an external service are added as GDScript packages or GDExtensions only to projects that need them.
| Entry | Purpose | Setup |
|---|---|---|
Discord | Pure-GDScript text bots on the Discord Gateway and REST | gd add @gd/discord |
GDSupabase | Database and Auth client | gd add ext:@gd/supabase |
Browse published packages in the package list. Because they are optional, they are not part of the API reference generated from the core.
gd add are trusted and loaded at startup, so no flag is needed. Under --strict, their target needs --allow-net.--allow-ext and --deny-ext apply when a script loads one while running with GDExtensionManager.load_extension().gd.lock and commit it.To use a package someone else published, create gd.json with gd init and then add the package. Find published packages in the package list or with gd search.
gd init
gd add hello
| Goal | Command |
|---|---|
| Search | gd search discord |
| Add | gd add hello (gd install hello does the same) |
| Choose the scope or a version range | gd add @gd/hello@^0.8.0 |
| Add under a name you choose | gd add greet @gd/hello |
| Add a native extension | gd add ext:@gd/supabase |
| Add from a URL or a local directory | gd add util https://example.com/util.gd, gd add ../mylib |
| Restore the same versions elsewhere | gd install --frozen |
| Check for and move to newer versions | gd outdated, gd update |
| Remove | gd uninstall hello |
| List what is installed | gd info |
Dependencies are recorded in gd.json (what you use) and gd.lock (which versions). Commit both. gd install without arguments restores the dependencies in gd.json; --frozen, --cached-only, and --sync apply to that restore.
Read an installed package by writing @import alias at the top of a script.
@import hello
pkg://<alias>/); nothing is copied into the project.gd.json but absent from the cache is fetched on the first run. Under --strict the registry needs --allow-net.gd add hello is looked up in the registry. When two or more packages share the name, gd asks which one to use.gd add is the package name with - and . turned into _, so it is an identifier. Aliases that are engine classes or keywords are refused.gd.json and gd.lock. gd init writes pkg/ into .gitignore.--frozen does not change the lock. For an offline target, fetch first where a network is available, and add --cached-only.gd install -g installs a package or script as a command such as my-tool. It leaves the gd.json and gd.lock of the project you are in untouched.
gd install -g tool # Install a published package by its short name.
gd install -g @scope/tool@1.0.0 # Choose the scope and version.
gd install -g --name my-tool ./tool.gd # Install a local script.
gd uninstall -g my-tool
| Flag | Meaning |
|---|---|
-n / --name | Command name. Defaults to the package or script name (the parent directory name for main.gd or mod.gd) |
--root <dir> | Install location. Defaults to GD_INSTALL_ROOT, then the default cache. Add its bin/ to PATH |
-f / --force | Update an installed command |
-- args | Fixed arguments passed first on every launch |
tool is looked up in the registry. When two or more packages share the name, gd lists them and asks which one to use. Writing @scope/tool skips the question.main(args). A published package uses mod.gd; a local directory uses main in its gd.json.--allow-* and --mount given at install time apply on every launch.--root by passing the same --root.@import is the short form of const Name = preload(...).
It is useful even without external dependencies: see samples/packages for a real registry dependency and its lockfile.
@import greet
@import "./util"
@import greet/style as theme
imports of gd.json. Files with the same name are not searched../ or ../. The .gd extension is optional. If a file and directory share a name, specify the file as "./util.gd".as, the identifier is the last segment as written, and a directory holding mod.gd binds its directory name.gd fmt keeps @import as it is.@import, so files shared with Godot should spell out const and preload.A package is one project rooted at its gd.json. gd init @scope/name seeds mod.gd and a test, gd test runs it, and gd publish releases it.
{"name":"@scope/hello","version":"1.0.0","main":"src/mod.gd","include":["src"]}
Package files are distributed from the author's GitHub Release. The registry keeps only where the files are and their fingerprints (SHA-256).
gd publish # Write the release files to tmp/release/scope-hello-1.0.0/.
gh release create 1.0.0 tmp/release/scope-hello-1.0.0/*
gd publish https://github.com/OWNER/REPO/releases/download/1.0.0
gd add hello gd:@scope/hello@^1.0.0
1. gd publish without an argument writes the files to publish to tmp/release/<scope>-<name>-<version>/. Each file is named by the SHA-256 of its contents. 2. Upload them as assets of a GitHub Release. Files of several packages or versions can share one release without name clashes. 3. Run gd publish with the release's download URL. gd fetches each file from the URL, confirms it matches the local one, and then lists the version in the registry.
Packages submitted to the public registry become searchable and installable after review. When gd publish prints a review ID, the version remains private until accepted. The registry checks the release files again just before acceptance.
mod.gd. For multiple files, list files or directories in include.imports of its own gd.json. gd publish records those imports in the registry.class_name may be published. Installation checks for conflicts between classes of the same name and rolls everything back on a conflict.godot to true in gd.json is the author's declaration that the package runs on upstream Godot without gd's own API, and gd search marks it [godot].A package under development is added from a local path with gd add ../path. Its alias comes from the name in its gd.json. The checkout is copied under pkg/<alias>/ and copied again on the next run whenever its content fingerprint changes. Files starting with ., pkg/, tmp/, subdirectories holding a gd.json, and token are not copied. gd publish turns a local import into its registry range when the target's gd.json has name and version, and refuses it otherwise.
Start the real registry on loopback from the repository. It saves the registry's records under tmp/dev-channel/data.
export GD_TOKEN='development token'
uv run --no-project python -B devtools/channel.py serve --scope dev --port 8787
In another terminal, set GD_REGISTRY=http://127.0.0.1:8787 and the same GD_TOKEN. Run gd publish --dry-run and gd publish from an @dev/name package. Serve the written files from loopback, for example with python3 -m http.server 8788 --bind 127.0.0.1 --directory tmp/release, and list them with gd publish http://127.0.0.1:8788/dev-name-1.0.0. Only development registries accept loopback HTTP. Consumers using that GD_REGISTRY can run gd search, gd add, gd install, gd install -g, and gd compile. A project's registry in gd.json takes precedence over the environment.
gd install resolves the whole dependency graph. It picks a version in this order: the version gd.lock pins, a version already chosen this time that satisfies the range, then the newest match in the registry.
gd.lock also records the resolved imports configuration. A run after a configuration change uses the same resolver instead of silently loading an outdated version. --frozen rejects mismatched requests. When multiple aliases name one package, the lexicographically first alias selects its copy directory.
pkg://@scope/name@version/. pkg://<alias>/ expands to it through the imports of the package the script belongs to. The same alias may name different versions in different packages, and one version is one script however it is reached.gd.lock also records each package's resolved imports, and gd info lists them.gd uninstall and gd update drop what no package uses any more from gd.lock and pkg/.To share a project with tools that only read res://, such as upstream Godot, set "place": "project" in gd.json. Packages are copied under pkg/<alias>/, and both pkg:// and res://pkg/ point there. A package that only other packages use goes under pkg/@scope/name@version/.
gd install --godot copies packages under addons/<alias>/. Also pass --godot to add, update, uninstall, and info. An addons/ directory inside a package does not cause the rest of the package to be excluded.project.godot exists, place defaults to project and no .gitignore is written. Commit pkg/ so teammates without gd can open the project.res:// references written in preload, load, and extends to the placement. Strings, comments, and paths built at run time are not rewritten.place only selects where files live. It does not convert gd's own API or syntax for Godot. Shared source should use standard syntax and relative preloads.pkg/<alias>/ whatever place is.ext:: the project's gd.json for project scripts, the package's own imports for package scripts.[classes] stops startup.gd compile on the target OS.gd.json has these eleven settings.
| Name | Written by gd init / when omitted | Meaning |
|---|---|---|
name | my-tool / required | Project name. Publishing needs @scope/name |
version | 0.1.0 / required | Package version |
tasks | run and test / none | Commands invoked by gd task |
imports | {} / {} | Alias and dependency source. A published package may name registry packages only |
registry | omitted / environment or the public registry | Registry URL pinned to the project |
main | omitted / mod.gd | mod.gd or .gdextension entry published |
include | omitted / main only | Files or directories inside the main directory included in a pure GDScript package |
place | omitted / cache, or project beside project.godot | Where packages live. project copies them under pkg/ |
godot | omitted / false | Declares a package that runs on upstream Godot without gd's own API |
description | omitted / empty | Description shown in the registry |
assets | omitted / none | Godot asset management alias and channel:publisher/slug[@version]; installed into addons/ |
gd reads these environment variables. A script that reads the environment needs the names allowed with --allow-env.
| Variable | Purpose |
|---|---|
GD_CACHE_HOME | Package cache root. Defaults to gd in Windows LocalAppData. On macOS/Linux, uses an absolute XDG_CACHE_HOME plus /gd, or .gd under the home directory. The OS account directory is used when HOME is unset |
GD_INSTALL_ROOT | Where gd install -g places commands. --root wins |
GD_USER_HOME | Absolute path for user://. By default it is created per script directory in the OS user data folder (~/Library/Application Support/gd/user on macOS, ~/.local/share/gd/user on Linux, %APPDATA%/gd/user on Windows) |
GD_REGISTRY | Registry. Defaults to https://gd.progsha.com/pkg. registry in gd.json wins |
GD_RELEASES | Release source read by gd upgrade. Defaults to https://github.com/prog-sha/gd/releases |
GD_TOKEN | Publish token. Keep it out of config files and pass it only to the publishing process |
LC_ALL, LANG | Language of the manual shown by gd doc |
GD_WORKER | Internal mark set by --workers. Not a user setting |
Remote packages and registries use HTTPS. A development registry on loopback may also use HTTP. Fetched packages and native libraries are checked against the SHA-256 in the registry index. All files in a package are limited to 500 MiB in total.
compile collects scripts, views, static files, migrations, dependency packages, and the target OS's GDExtensions into one executable. The target needs no cache.
gd compile -o app main.gd
./app
gd.json names, and every package those import, is embedded../app serve --no-scene-tree --allow-net.. such as .env and the token in gd.json are left out..env, but values written in source remain in the executable.gd search includes packages, the public Godot asset catalog, and the reviewed gd catalog. A project using a custom registry searches only that registry.
| Channel | Source |
|---|---|
official | Godot Asset Store |
gd | Reviewed gd assets |
Copy an asset:channel:publisher/name result directly into gd add.
gd search dialog
gd add asset:official:publisher/dialog
gd add ui asset:gd:publisher/dialog@1.2.0
gd install --frozen --cached-only
gd update ui
gd uninstall ui
asset:official:publisher/dialog@#123. Quote the complete argument when a label contains spaces.official. Failure never redirects resolution to another catalog.gd.json records requests under assets; gd.lock pins the origin, version and SHA-256. Commit both files.asset: copy the ZIP's addons/ tree into the project's addons/. Asset aliases are management names. Ordinary packages are recorded under imports and loaded with @import.@1.2.0 remains fixed during update.--frozen preserves the lock; --cached-only performs no network requests. Fetch archives before moving offline.The source distribution also includes a catalog inspection client:
gd tools/store.gd channels
gd tools/store.gd search official 4.7 dialog
gd tools/store.gd show gd publisher dialog
gd tools/store.gd releases gd publisher dialog
gd is a public release before the API has settled. Do not assume backward compatibility. Changes and the Godot version used as the base are recorded in the CHANGELOG. gd is not an official product of the Godot Foundation or the Godot Engine project.
Report bugs in Issues. Report vulnerabilities that should not be public through GitHub private reporting.
The features below are still in development. Their usage and behavior may change without notice. Treat this section as a preview.
gd editor opens the editor. The first run installs gd-godot, the executable that provides the window.
| Goal | Command |
|---|---|
| Open the editor | gd editor |
| Open a chosen project | gd editor <project directory> |
| Run a project in a window | gd run-game <project directory> |
See the gd-godot manual for details.
GD.online.match() creates a server that finds opponents for online games. Rooms announce their address and player count, and joining players receive one room with free seats. State lives in process memory, or in a key-value server shared by several processes. Marking variables with @online to synchronize state between server and clients is also in preparation.
gdの関数やオブジェクトについて、引数と戻り値を一覧にしています。Godot由来の型はGodotのクラスリファレンスを参照してください。
Signatures of gd's own entry points and of the objects they return. For Godot classes, see the Godot class reference.
一致するAPIがありません。No matching API.
ファイル、データ変換、非同期処理、日時など、コマンドラインのプログラムで使う標準機能をまとめています。
Entry to the standard features of a command-line program: files, data, async, time, and more.
async: GD.asynclog: GD.lognet: GD.netmail: GD.mailhttp: GD.httpweb: GD.webfile: GD.filecollection: GD.collectiondata: GD.dataid: GD.idtext: GD.texthtml: GD.htmlmath: GD.mathversion: GD.versiontime: GD.timecli: GD.clitest: GD.testdatabase: GD.databaseonline: GD.online非同期処理を開始したり、複数の処理の完了を待ったり、タイムアウトやキャンセルを扱ったりします。最初に完了した処理の結果を受け取ることもできます。spawnは関数をメインスレッド上で開始します。大きなデータの計算には、各標準モジュールの_async付き関数を使います。
Entry for async work: waiting, concurrency, racing, timeouts, and cancellation. spawn starts a main-thread coroutine; CPU work belongs in each standard module's _async entry points.
set_max_threads(max: int) -> intsleep(sec: float) -> GDTask (await Variant)spawn(fn: Callable) -> GDTask (await Variant)spawn_pair(fn: Callable) -> GDTask (await Variant, Err)call_pair(fn: Callable) -> Variant, Errall(tasks: Array) -> GDTask (await Array)race(tasks: Array) -> GDTask (await int)with_timeout(task: Variant, sec: float) -> GDTask (await int)with_context(context: GDAsyncContext, task: Variant) -> GDTask (await Variant)with_context_pair(context: GDAsyncContext, task: Variant) -> GDTask (await Variant, Err)context() -> GDAsyncContext重要度、時刻、出力先を指定してログを記録します。1行ずつ順番に書き込み、各呼び出しは完了を待って値とErrを返します。flushで、それまでの出力が終わるのを待てます。
Entry for ordered I/O of one line at a time with a consistent level, time, and destination. flush waits for earlier output.
setup(name: String = "", level: String = "info") -> voidset_file(path: String) -> voidset_time(on: bool) -> voidset_color(on: bool) -> voidwrite(level: String, msg: String, extra: Variant = null) -> Variant, Errdebug(msg: String, extra: Variant = null) -> Variant, Errinfo(msg: String, extra: Variant = null) -> Variant, Errwarn(msg: String, extra: Variant = null) -> Variant, Errerror(msg: String, extra: Variant = null) -> Variant, Errresult(error: Err, msg: String) -> Variant, Errwrite_async(level: String, msg: String, extra: Variant = null) -> GDTask (await Variant, Err)debug_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)info_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)warn_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)error_async(msg: String, extra: Variant = null) -> GDTask (await Variant, Err)result_async(error: Err, msg: String) -> GDTask (await Variant, Err)format(level: String, msg: String, extra: Variant = null) -> Stringflush() -> Variant, Errflush_async() -> GDTask (await Variant, Err)TCP・TLSの接続、接続の待ち受け、UDP通信、名前解決、アドレスの検査を行います。TLSでは既定で証明書チェーンと接続先のホスト名を検証します。完了を待つのは、呼び出した処理だけです。
Network entry for TCP and TLS streams, listeners, UDP packets, name resolution, and address checks. TLS verifies the certificate chain and server name by default; waiting operations suspend only their caller.
is_free(port: int, host: String = "127.0.0.1") -> boolfree_port(from: int = 0, host: String = "127.0.0.1") -> int, Errresolve(host: String) -> String, Errresolve_async(host: String) -> GDTask (await String, Err)dial_tcp(host: String, port: int, opts: Dictionary = { }) -> GDTCPConn, Errdial_tcp_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)dial_tls(host: String, port: int, opts: Dictionary = { }) -> GDTCPConn, Errdial_tls_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)listen_tcp(host: String = "127.0.0.1", port: int = 0) -> GDTCPListener, Errlisten_udp(host: String = "127.0.0.1", port: int = 0, buffer: int = 0) -> GDUDPPacketConn, Erris_free_async(port: int, host: String = "127.0.0.1") -> GDTask (await bool)free_port_async(from: int = 0, host: String = "127.0.0.1") -> GDTask (await int, Err)local_addresses() -> PackedStringArray, Errlocal_addresses_async() -> GDTask (await PackedStringArray, Err)is_ip(text: String) -> boolsplit_host(text: String, default_port: int = 80) -> Dictionaryメールアドレス、日付、ヘッダーを解析し、SMTPサーバーへメールを送ります。STARTTLSは既存接続を暗号化し、失敗時は平文へ戻りません。MIMEの機能はGD.mail.mimeにあります。
Parse mail addresses, dates, and headers, and submit messages over SMTP. STARTTLS upgrades the existing connection without falling back to plaintext. MIME helpers are under GD.mail.mime.
mime: GD.mail.mimeparse_address(text: String) -> Dictionary, Errparse_address_list(text: String) -> Array, Errparse_date(text: String) -> Dictionary, Errread_message(data: PackedByteArray) -> GDMailMessage, Errread_message_async(source: Variant) -> GDTask (await GDMailMessage, Err)plain_auth(user: String, password: String, identity: String = "") -> Dictionarycram_md5_auth(user: String, secret: String) -> Dictionarycram_md5(key: PackedByteArray, challenge: PackedByteArray) -> String, Errdial_smtp(host: String, port: int, opts: Dictionary = { }) -> GDSMTPClient, Errdial_smtp_async(host: String, port: int, opts: Dictionary = { }) -> GDTask (await GDSMTPClient, Err)send_mail(host: String, port: int, from: String, to: PackedStringArray, message: PackedByteArray, opts: Dictionary = { }) -> Variant, Errsend_mail_async(host: String, port: int, from: String, to: PackedStringArray, message: PackedByteArray, opts: Dictionary = { }) -> GDTask (await Variant, Err)HTTPリクエストの送信、URL・クエリ文字列・メディアタイプの組み立てと解析を行います。fetchは呼び出した処理だけを待たせ、fetch_asyncはGDTaskを返します。
Entry for HTTP requests plus URL, query, and media-type handling. fetch suspends only its caller; fetch_async returns a GDTask for composition.
設定Settings: timeout max_body method authority headers body save sha256
fetch(url: String, opts: Dictionary = { }) -> GDHTTPResponse, Errfetch_async(url: String, opts: Dictionary = { }) -> GDTask (await GDHTTPResponse, Err)parse_url(raw: String) -> Dictionary, Errparse_url_async(raw: String) -> GDTask (await Dictionary, Err)build_url(url: Dictionary) -> Stringbuild_url_async(url: Dictionary) -> GDTask (await String)request_target(url: Dictionary) -> Stringrequest_target_async(url: Dictionary) -> GDTask (await String)default_port(scheme: String) -> intdecode_query(raw: String) -> Dictionary, Errdecode_query_async(raw: String) -> GDTask (await Dictionary, Err)encode_query(query: Dictionary) -> Stringencode_query_async(query: Dictionary) -> GDTask (await String)media_type(path: String) -> Stringmedia_type_for_extension(ext: String) -> Stringis_textual(kind: String) -> boolextension_for_media_type(kind: String) -> StringWebサイトやWeb APIを作るための機能です。URLと処理の対応付け、静的ファイル配信、HTMLテンプレート、セッション、CSRF対策、JWT認証、リクエスト数の制限、入力検査を利用できます。
Entry for building websites and Web APIs, with routes, static files, gdhtml templates, sessions, CSRF, JWT, rate limiting, and input validation.
設定Settings: ttl leeway require_exp iss aud keep total per_user idle life cookie limit keys window key allow_missing min max extra
text(body: String, status: int = 200) -> GDWebResponsehtml(body: String, status: int = 200) -> GDWebResponsejson(data: Variant, status: int = 200) -> GDWebResponse, Errbytes(body: PackedByteArray, type: String = "application/octet-stream", status: int = 200) -> GDWebResponsestream(producer: Callable, length: int = -1, type: String = "application/octet-stream", status: int = 200) -> GDWebResponseredirect(to: String, status: int = 302, away: bool = false) -> GDWebResponseguard(reply: GDWebResponse) -> GDWebResponsenot_found(msg: String = "Not Found") -> GDWebResponseheader(reply: GDWebResponse, name: String, value: Variant) -> GDWebResponseadd_header(reply: GDWebResponse, name: String, value: Variant) -> GDWebResponseview(path: String, data: Dictionary = { }, status: int = 200, renderer: Callable = null) -> GDWebResponse, Errview_async(path: String, data: Dictionary = { }, status: int = 200, renderer: Callable = null) -> GDTask (await GDWebResponse, Err)json_async(data: Variant, status: int = 200) -> GDTask (await GDWebResponse, Err)error_status(error: Err) -> intjwt(key: Variant, opts: Dictionary = { }) -> GDWebMiddlewarejwt_sign(claims: Dictionary, key: Variant, opts: Dictionary = { }) -> String, Errjwt_verify(token: String, key: Variant, opts: Dictionary = { }) -> Dictionary, Errjwt_sign_async(claims: Dictionary, key: Variant, opts: Dictionary = { }) -> GDTask (await String, Err)jwt_verify_async(token: String, key: Variant, opts: Dictionary = { }) -> GDTask (await Dictionary, Err)csrf(opts: Dictionary = { }) -> GDWebMiddlewaresessions(opts: Dictionary = { }) -> GDWebSessionStorerate(opts: Dictionary = { }) -> GDWebMiddlewaretext_rule(opts: Dictionary = { }) -> Dictionaryint_rule(opts: Dictionary = { }) -> Dictionarynumber_rule(opts: Dictionary = { }) -> Dictionarybool_rule() -> Dictionarylist_rule(item: Dictionary = { }, opts: Dictionary = { }) -> Dictionaryobject_rule(fields: Dictionary, opts: Dictionary = { }) -> Dictionaryoptional(rule: Dictionary, fallback: Variant = null) -> Dictionaryone_of(values: Array) -> Dictionaryvalidate(value: Variant, rule: Dictionary) -> Variant, Errvalidate_async(value: Variant, rule: Dictionary) -> GDTask (await Variant, Err)json_body(rule: Dictionary, name: String = "body") -> GDWebMiddlewarequery(rule: Dictionary, name: String = "query") -> GDWebMiddlewareparams(rule: Dictionary, name: String = "params") -> GDWebMiddlewareファイルの読み書き、パスの操作、各種データ形式の読み取りを行います。ファイル全体を扱う場合も少しずつ読み書きする場合も、呼び出した処理だけが完了を待ちます。_async付きの関数はGDTaskを返します。
Whole-file operations and streaming file I/O suspend only their caller. This entry also provides path operations and file-format readers; *_async returns a GDTask for concurrent starts.
open(path: String, mode: String = "read") -> GDFileStream, Erropen_async(path: String, mode: String = "read") -> GDTask (await GDFileStream, Err)read_text(path: String) -> String, Errread_bytes(path: String, offset: int = 0, max: int = 0) -> PackedByteArray, Errwrite_text(path: String, body: String) -> Variant, Errreplace_text(path: String, old: Variant, body: String) -> Variant, Errwrite_bytes(path: String, body: PackedByteArray) -> Variant, Errappend_bytes(path: String, body: PackedByteArray) -> Variant, Errappend_text(path: String, body: String) -> Variant, Errexists(path: String) -> boolremove(path: String) -> Variant, Errsize_of(path: String) -> int, Errcopy(src: String, dst: String) -> Variant, Errrename(src: String, dst: String) -> Variant, Errlist_dir(path: String) -> Array, Errmake_dir(path: String) -> Variant, Errensure_dir(path: String) -> Variant, Errwalk(path: String, want_dirs: bool = false, hidden: bool = false) -> Array, Errglob(path: String, pattern: String, hidden: bool = false) -> Array, Errremove_all(path: String) -> Variant, Errcan_read(path: String) -> boolread_text_async(path: String) -> GDTask (await String, Err)read_bytes_async(path: String, offset: int = 0, max: int = 0) -> GDTask (await PackedByteArray, Err)write_text_async(path: String, body: String) -> GDTask (await Variant, Err)write_bytes_async(path: String, body: PackedByteArray) -> GDTask (await Variant, Err)append_text_async(path: String, body: String) -> GDTask (await Variant, Err)append_bytes_async(path: String, body: PackedByteArray) -> GDTask (await Variant, Err)copy_async(src: String, dst: String) -> GDTask (await Variant, Err)replace_text_async(path: String, old: Variant, body: String) -> GDTask (await Variant, Err)exists_async(path: String) -> GDTask (await bool)remove_async(path: String) -> GDTask (await Variant, Err)size_of_async(path: String) -> GDTask (await int, Err)rename_async(src: String, dst: String) -> GDTask (await Variant, Err)list_dir_async(path: String) -> GDTask (await Array, Err)make_dir_async(path: String) -> GDTask (await Variant, Err)ensure_dir_async(path: String) -> GDTask (await Variant, Err)walk_async(path: String, want_dirs: bool = false, hidden: bool = false) -> GDTask (await Array, Err)glob_async(path: String, pattern: String, hidden: bool = false) -> GDTask (await Array, Err)remove_all_async(path: String) -> GDTask (await Variant, Err)can_read_async(path: String) -> GDTask (await bool)parse_path(path: String) -> Dictionaryformat_path(parts: Dictionary) -> Stringjoin(parts: PackedStringArray) -> Stringdirname(path: String) -> Stringbasename(path: String, suffix: String = "") -> Stringextname(path: String) -> Stringis_absolute(path: String) -> boolnormalize(path: String) -> Stringrelative(from: String, to: String) -> Stringunder(dir: String, name: String) -> Stringcreate_tar(root: String) -> PackedByteArray, Errextract_tar(data: PackedByteArray, root: String) -> int, Errread_csv(path: String, sep: String = ",") -> Array, Errread_ini(path: String) -> Dictionary, Errread_toml(path: String) -> Dictionary, Errread_yaml(path: String) -> Variant, Errread_jsonc(path: String) -> Variant, Errread_jsonl(path: String) -> Array, Errread_front_matter(path: String) -> Dictionary, Errread_xml(path: String) -> Dictionary, Errread_env(path: String = ".env") -> Dictionary, Errread_tar(path: String) -> Array, Errread_csv_async(path: String, sep: String = ",") -> GDTask (await Array, Err)read_ini_async(path: String) -> GDTask (await Dictionary, Err)read_toml_async(path: String) -> GDTask (await Dictionary, Err)read_yaml_async(path: String) -> GDTask (await Variant, Err)read_jsonc_async(path: String) -> GDTask (await Variant, Err)read_jsonl_async(path: String) -> GDTask (await Array, Err)read_front_matter_async(path: String) -> GDTask (await Dictionary, Err)read_xml_async(path: String) -> GDTask (await Dictionary, Err)read_env_async(path: String = ".env") -> GDTask (await Dictionary, Err)read_tar_async(path: String) -> GDTask (await Array, Err)create_tar_async(root: String) -> GDTask (await PackedByteArray, Err)extract_tar_async(data: PackedByteArray, root: String) -> GDTask (await int, Err)配列や辞書の変換、ヒープ、キュー、キャッシュを扱います。時間のかかる処理は別スレッド、またはほかの処理と交代しながら進めます。Callableを使う操作も、SceneTreeのフレームを待たずにほかのタスクへ実行を譲ります。
Reshape Arrays and Dictionaries and create heaps, queues, and caches. Awaitable operations use CPU workers or the runtime ready queue; callable work cooperates with other tasks without requiring SceneTree frames.
group_by(items: Array, key: Callable) -> Dictionarymap_values(src: Dictionary, fn: Callable) -> Dictionaryfilter_keys(src: Dictionary, pred: Callable) -> Dictionarypartition(items: Array, pred: Callable) -> Arraychunk(items: Array, size: int) -> Arrayunique_by(items: Array, key: Callable) -> Arrayunique(items: Array) -> Arraysort_by(items: Array, pick: Callable) -> Arraysort_key(items: Array, key: String) -> Arrayzip(a: Array, b: Array) -> Arraysum_of(items: Array, pick: Callable) -> floatmax_by(items: Array, pick: Callable) -> Variantmin_by(items: Array, pick: Callable) -> Variantindex_by(items: Array, key: Callable) -> Dictionarydeep_merge(base: Dictionary, over: Dictionary) -> Dictionarybinary_heap(pick: Callable = null) -> GDBinaryHeappriority_queue() -> GDPriorityQueuelru_cache(limit: int = 128, ttl_ms: int = 0) -> GDLRUCachememo(fn: Callable, limit: int = 128) -> GDMemoizedCallablegroup_by_async(items: Array, key: Callable) -> GDTask (await Dictionary)map_values_async(src: Dictionary, fn: Callable) -> GDTask (await Dictionary)filter_keys_async(src: Dictionary, pred: Callable) -> GDTask (await Dictionary)partition_async(items: Array, pred: Callable) -> GDTask (await Array)unique_by_async(items: Array, key: Callable) -> GDTask (await Array)sort_by_async(items: Array, pick: Callable) -> GDTask (await Array)sum_of_async(items: Array, pick: Callable) -> GDTask (await float)max_by_async(items: Array, pick: Callable) -> GDTask (await Variant)min_by_async(items: Array, pick: Callable) -> GDTask (await Variant)index_by_async(items: Array, key: Callable) -> GDTask (await Dictionary)chunk_async(items: Array, size: int) -> GDTask (await Array)unique_async(items: Array) -> GDTask (await Array)sort_key_async(items: Array, key: String) -> GDTask (await Array)zip_async(a: Array, b: Array) -> GDTask (await Array)deep_merge_async(base: Dictionary, over: Dictionary) -> GDTask (await Dictionary)バイト列、データ形式の変換、ハッシュ、鍵の生成を扱います。CSV・INI・TOML・YAML・JSON・XMLなどをメモリ上で変換できます。不正な入力や設定はエラーとして返します。
Data conversion for bytes, binary codecs, hashes, key derivation, and in-memory CSV, INI, TOML, YAML, JSON, XML, and related formats. Invalid input and settings return failures.
gzip_writer(writer: RefCounted, level: int = -1) -> GDGzipWriter, Errsha224(msg: PackedByteArray) -> PackedByteArraysha256(msg: PackedByteArray) -> PackedByteArraysha384(msg: PackedByteArray) -> PackedByteArraysha512(msg: PackedByteArray) -> PackedByteArraysha3_224(msg: PackedByteArray) -> PackedByteArraysha3_256(msg: PackedByteArray) -> PackedByteArraysha3_384(msg: PackedByteArray) -> PackedByteArraysha3_512(msg: PackedByteArray) -> PackedByteArraysha1(msg: PackedByteArray) -> PackedByteArrayhmac(hash: String, key: PackedByteArray, msg: PackedByteArray) -> PackedByteArray, Errhmac_sha256(key: PackedByteArray, msg: PackedByteArray) -> PackedByteArrayequal_ct(a: PackedByteArray, b: PackedByteArray) -> boolpbkdf2_sha256(password: PackedByteArray, salt: PackedByteArray, rounds: int) -> PackedByteArray, Errpbkdf2(hash: String, password: PackedByteArray, salt: PackedByteArray, rounds: int, size: int) -> PackedByteArray, Errhkdf(hash: String, secret: PackedByteArray, salt: PackedByteArray, info: PackedByteArray, size: int) -> PackedByteArray, Errhkdf_extract(hash: String, secret: PackedByteArray, salt: PackedByteArray) -> PackedByteArray, Errhkdf_expand(hash: String, key: PackedByteArray, info: PackedByteArray, size: int) -> PackedByteArray, Errpbkdf2_sha256_async(password: PackedByteArray, salt: PackedByteArray, rounds: int) -> GDTask (await PackedByteArray, Err)pbkdf2_async(hash: String, password: PackedByteArray, salt: PackedByteArray, rounds: int, size: int) -> GDTask (await PackedByteArray, Err)hkdf_async(hash: String, secret: PackedByteArray, salt: PackedByteArray, info: PackedByteArray, size: int) -> GDTask (await PackedByteArray, Err)hkdf_extract_async(hash: String, secret: PackedByteArray, salt: PackedByteArray) -> GDTask (await PackedByteArray, Err)hkdf_expand_async(hash: String, key: PackedByteArray, info: PackedByteArray, size: int) -> GDTask (await PackedByteArray, Err)sha224_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha256_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha384_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha512_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha3_224_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha3_256_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha3_384_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha3_512_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)sha1_async(msg: PackedByteArray) -> GDTask (await PackedByteArray)hmac_async(hash: String, key: PackedByteArray, msg: PackedByteArray) -> GDTask (await PackedByteArray, Err)hmac_sha256_async(key: PackedByteArray, msg: PackedByteArray) -> GDTask (await PackedByteArray)equal_ct_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await bool)csv(src: String, sep: String = ",") -> Array, Errto_csv(rows: Array, sep: String = ",") -> Stringcsv_objects(src: String, sep: String = ",") -> Array, Errto_csv_objects(items: Array, sep: String = ",") -> Stringini(src: String) -> Dictionary, Errto_ini(data: Dictionary) -> Stringtoml(src: String) -> Dictionary, Errto_toml(data: Dictionary, prefix: String = "") -> String, Erryaml(src: String) -> Variant, Errto_yaml(data: Variant, depth: int = 0) -> String, Errjsonc(src: String) -> Variant, Errstrip_jsonc(src: String) -> Stringjsonl(src: String) -> Array, Errto_jsonl(items: Array) -> String, Errjsonl_reader() -> GDJSONLReaderfront_matter(src: String) -> Dictionary, Errhas_front_matter(src: String) -> boolto_front_matter(attrs: Dictionary, body: String, kind: String = "yaml") -> String, Errxml(src: String) -> Dictionary, Errto_xml(data: Dictionary, indent: int = 0) -> String, Errenv(src: String) -> Dictionary, Errto_env(data: Dictionary) -> String, Errtar(entries: Array) -> PackedByteArray, Erruntar(data: PackedByteArray) -> Array, Errjson_encode(value: Variant, opts: Dictionary = { }) -> PackedByteArray, Errjson_decode(data: PackedByteArray) -> Variant, Errmsgpack(value: Variant) -> PackedByteArray, Errunmsgpack(data: PackedByteArray) -> Variant, Errcbor(value: Variant) -> PackedByteArray, Erruncbor(data: PackedByteArray) -> Variant, Errjson_encode_async(value: Variant, opts: Dictionary = { }) -> GDTask (await PackedByteArray, Err)json_decode_async(data: PackedByteArray) -> GDTask (await Variant, Err)msgpack_async(value: Variant) -> GDTask (await PackedByteArray, Err)unmsgpack_async(data: PackedByteArray) -> GDTask (await Variant, Err)cbor_async(value: Variant) -> GDTask (await PackedByteArray, Err)uncbor_async(data: PackedByteArray) -> GDTask (await Variant, Err)csv_async(src: String, sep: String = ",") -> GDTask (await Array, Err)to_csv_async(rows: Array, sep: String = ",") -> GDTask (await String)csv_objects_async(src: String, sep: String = ",") -> GDTask (await Array, Err)to_csv_objects_async(items: Array, sep: String = ",") -> GDTask (await String)ini_async(src: String) -> GDTask (await Dictionary, Err)to_ini_async(data: Dictionary) -> GDTask (await String)toml_async(src: String) -> GDTask (await Dictionary, Err)to_toml_async(data: Dictionary, prefix: String = "") -> GDTask (await String, Err)yaml_async(src: String) -> GDTask (await Variant, Err)to_yaml_async(data: Variant, depth: int = 0) -> GDTask (await String, Err)jsonc_async(src: String) -> GDTask (await Variant, Err)strip_jsonc_async(src: String) -> GDTask (await String)jsonl_async(src: String) -> GDTask (await Array, Err)to_jsonl_async(items: Array) -> GDTask (await String, Err)front_matter_async(src: String) -> GDTask (await Dictionary, Err)to_front_matter_async(attrs: Dictionary, body: String, kind: String = "yaml") -> GDTask (await String, Err)xml_async(src: String) -> GDTask (await Dictionary, Err)to_xml_async(data: Dictionary, indent: int = 0) -> GDTask (await String, Err)env_async(src: String) -> GDTask (await Dictionary, Err)to_env_async(data: Dictionary) -> GDTask (await String, Err)tar_async(entries: Array) -> GDTask (await PackedByteArray, Err)untar_async(data: PackedByteArray) -> GDTask (await Array, Err)hex_encode(data: PackedByteArray) -> Stringhex_decode(text: String) -> PackedByteArray, Errbase64_encode(data: PackedByteArray) -> Stringbase64_decode(text: String, raw: bool = false) -> PackedByteArray, Errbase64url_encode(data: PackedByteArray) -> Stringbase64url_decode(text: String, raw: bool = true) -> PackedByteArray, Errbase32_encode(data: PackedByteArray) -> Stringbase32_decode(text: String, raw: bool = false) -> PackedByteArray, Errvarint_encode(n: int) -> PackedByteArrayvarint_decode(data: PackedByteArray, at: int = 0) -> Dictionary, Errhex_encode_async(data: PackedByteArray) -> GDTask (await String)hex_decode_async(text: String) -> GDTask (await PackedByteArray, Err)base64_encode_async(data: PackedByteArray) -> GDTask (await String)base64_decode_async(text: String, raw: bool = false) -> GDTask (await PackedByteArray, Err)base64url_encode_async(data: PackedByteArray) -> GDTask (await String)base64url_decode_async(text: String, raw: bool = true) -> GDTask (await PackedByteArray, Err)base32_encode_async(data: PackedByteArray) -> GDTask (await String)base32_decode_async(text: String, raw: bool = false) -> GDTask (await PackedByteArray, Err)concat(parts: Array) -> PackedByteArrayequals(a: PackedByteArray, b: PackedByteArray) -> boolincludes(hay: PackedByteArray, needle: PackedByteArray) -> boolindex_of(hay: PackedByteArray, needle: PackedByteArray, from: int = 0) -> intlast_index_of(hay: PackedByteArray, needle: PackedByteArray) -> intstarts_with(hay: PackedByteArray, prefix: PackedByteArray) -> boolends_with(hay: PackedByteArray, suffix: PackedByteArray) -> boolrepeat(src: PackedByteArray, times: int) -> PackedByteArrayfit(src: PackedByteArray, size: int) -> PackedByteArraysplit(src: PackedByteArray, sep: PackedByteArray) -> Arrayxor_bytes(a: PackedByteArray, b: PackedByteArray) -> PackedByteArrayconcat_async(parts: Array) -> GDTask (await PackedByteArray)equals_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await bool)includes_async(hay: PackedByteArray, needle: PackedByteArray) -> GDTask (await bool)index_of_async(hay: PackedByteArray, needle: PackedByteArray, from: int = 0) -> GDTask (await int)last_index_of_async(hay: PackedByteArray, needle: PackedByteArray) -> GDTask (await int)starts_with_async(hay: PackedByteArray, prefix: PackedByteArray) -> GDTask (await bool)ends_with_async(hay: PackedByteArray, suffix: PackedByteArray) -> GDTask (await bool)repeat_async(src: PackedByteArray, times: int) -> GDTask (await PackedByteArray)fit_async(src: PackedByteArray, size: int) -> GDTask (await PackedByteArray)split_async(src: PackedByteArray, sep: PackedByteArray) -> GDTask (await Array)xor_bytes_async(a: PackedByteArray, b: PackedByteArray) -> GDTask (await PackedByteArray)UUIDと、時刻順に並べられるULIDを生成・検査します。ULID時刻の-1は現在時刻を選び、その他の48ビット範囲外は空文字を返します。範囲外の符号化文字列は拒否します。
Entry for generating and checking UUIDs and time-ordered ULIDs. Timestamp -1 selects the current time; other values outside the 48-bit range return an empty string. Encoded overflow is rejected.
ulid(ms: int = -1) -> Stringis_ulid(text: String) -> boolulid_time(text: String) -> int, Erruuid() -> Stringuuid_v5(space: String, name: String) -> String, Erruuid_v5_async(space: String, name: String) -> GDTask (await String, Err)is_uuid(text: String) -> booluuid_bytes(text: String) -> PackedByteArray, Erruuid_version(text: String) -> intnil_uuid() -> Stringdns_namespace() -> Stringurl_namespace() -> Stringoid_namespace() -> String文字列の整形と比較を行います。
Entry for formatting and comparing text.
closest(word: String, options: PackedStringArray) -> Stringellipsis(text: String, width: int) -> Stringsize_of(bytes: int) -> Stringduration(ms: float) -> Stringdistance(a: String, b: String) -> intsnake(text: String) -> Stringcamel(text: String) -> Stringtitle(text: String) -> Stringtable(rows: Array, gap: int = 2) -> Stringdistance_async(a: String, b: String) -> GDTask (await int)closest_async(word: String, options: PackedStringArray) -> GDTask (await String)ellipsis_async(text: String, width: int) -> GDTask (await String)snake_async(text: String) -> GDTask (await String)camel_async(text: String) -> GDTask (await String)title_async(text: String) -> GDTask (await String)table_async(rows: Array, gap: int = 2) -> GDTask (await String)HTMLの文字参照、タグ、テンプレートを扱います。テンプレートへ埋め込む値は、本文、属性、URL、スタイル、スクリプトのどこに使うかに応じてエスケープします。
Entry for HTML entities, tags, and templates with context-sensitive escaping for text, attributes, URLs, styles, and scripts.
fill(tpl: String, data: Dictionary, partials: Dictionary = { }) -> String, Errtemplate(tpl: String, partials: Dictionary = { }) -> GDHTMLTemplate, Errattr(value: String) -> Stringtag(name: String, body: String, attrs: Dictionary = { }) -> Stringescape(text: String) -> Stringunescape(text: String) -> Stringescape_async(text: String) -> GDTask (await String)unescape_async(text: String) -> GDTask (await String)attr_async(value: String) -> GDTask (await String)tag_async(name: String, body: String, attrs: Dictionary = { }) -> GDTask (await String)fill_async(tpl: String, data: Dictionary, partials: Dictionary = { }) -> GDTask (await String, Err)数学関数、IEEE 754の特殊な値、浮動小数点数とビット列の変換を扱います。
Entry for standard mathematical functions, IEEE 754 special values, and bit conversions.
bits: GD.math.bitse: floatpi: floatphi: floatsqrt2: floatsqrt_e: floatsqrt_pi: floatsqrt_phi: floatln2: floatlog2_e: floatln10: floatlog10_e: floatmax_float64: floatsmallest_nonzero_float64: floatabs(x: float) -> floatacos(x: float) -> floatacosh(x: float) -> floatasin(x: float) -> floatasinh(x: float) -> floatatan(x: float) -> floatatanh(x: float) -> floatcbrt(x: float) -> floatceil(x: float) -> floatcos(x: float) -> floatcosh(x: float) -> floaterf(x: float) -> floaterfc(x: float) -> floaterfinv(x: float) -> floaterfcinv(x: float) -> floatexp(x: float) -> floatexp2(x: float) -> floatexpm1(x: float) -> floatfloor(x: float) -> floatgamma(x: float) -> floatilogb(x: float) -> intj0(x: float) -> floatj1(x: float) -> floatlog(x: float) -> floatlog1p(x: float) -> floatlog2(x: float) -> floatlog10(x: float) -> floatlogb(x: float) -> floatround(x: float) -> floatround_to_even(x: float) -> floatsignbit(x: float) -> boolsin(x: float) -> floatsinh(x: float) -> floatsqrt(x: float) -> floattan(x: float) -> floattanh(x: float) -> floattrunc(x: float) -> floaty0(x: float) -> floaty1(x: float) -> floatfloat64_bits(x: float) -> intfloat64_from_bits(x: int) -> floatfloat32_bits(x: float) -> intfloat32_from_bits(x: int) -> floatnan() -> floatinf(sign: int) -> floatis_inf(x: float, sign: int = 0) -> boolis_nan(x: float) -> boolatan2(y: float, x: float) -> floatcopysign(value: float, sign: float) -> floatdim(x: float, y: float) -> floatfma(x: float, y: float, z: float) -> floathypot(x: float, y: float) -> floatldexp(frac: float, exp: int) -> floatmax(x: float, y: float) -> floatmin(x: float, y: float) -> floatmod(x: float, y: float) -> floatnextafter(x: float, y: float) -> floatnextafter32(x: float, y: float) -> floatpow(x: float, y: float) -> floatpow10(n: int) -> floatremainder(x: float, y: float) -> floatfrexp(x: float) -> Arraylgamma(x: float) -> Arraymodf(x: float) -> Arraysincos(x: float) -> Arrayセマンティックバージョンを解析・比較し、指定したバージョン範囲に含まれるか調べます。
Entry for parsing, comparing, and range-matching Semantic Versions.
parse(raw: String) -> Dictionary, Erris_canonical(raw: String) -> boolcompare(a: Dictionary, b: Dictionary) -> intis_stable(v: Dictionary) -> booltext(v: Dictionary) -> Stringbest(list: PackedStringArray, range: String = "*") -> Dictionary, Errbest_async(list: PackedStringArray, range: String = "*") -> GDTask (await Dictionary, Err)satisfies(v: Dictionary, range: String) -> boolUnix時刻、ISO 8601、HTTPの日付を変換・計算します。parse_isoはRFC 3339形式を受け取ります。加算や差分が64ビット整数の範囲を超える場合は、最大値または最小値になります。
Entry for converting and computing Unix time, ISO 8601, and HTTP dates. parse_iso accepts RFC 3339, and add and diff clamp at the 64-bit integer ends.
now() -> intto_parts(unix: int) -> Dictionaryfrom_parts(parts: Dictionary) -> intto_iso(unix: int) -> Stringto_http(unix: int) -> Stringparse_iso(text: String) -> int, Erradd(unix: int, amount: int, unit: String = "second") -> intdiff(a: int, b: int, unit: String = "second") -> intstart_of_day(unix: int) -> intweekday(unix: int) -> intis_leap(year: int) -> booldays_in_month(year: int, month: int) -> intago(unix: int, base: int = -1) -> Stringformat(unix: int, pattern: String) -> Stringgdのバージョンや文書の表示、コマンドライン引数、環境変数、システム情報の取得に使います。アクセス権限の設定に従います。
Entry for gd's version and docs, flags, and allowed environment and system information.
version() -> Stringdocs_url() -> Stringflags() -> GDCLIFlagsenv(name: String, fallback: Variant = null) -> Variantrequire_env(name: String) -> String, Errcwd() -> Stringplatform() -> Stringarch() -> Stringstdin_tty() -> boolstdout_tty() -> boolstderr_tty() -> boolpaint(text: String, code: int) -> Stringred(text: String) -> Stringgreen(text: String) -> Stringyellow(text: String) -> Stringblue(text: String) -> Stringgray(text: String) -> Stringbold(text: String) -> Stringrun(path: String, args: PackedStringArray = [], opts: Dictionary = { }) -> Dictionary, Errrun_async(path: String, args: PackedStringArray = [], opts: Dictionary = { }) -> GDTask (await Dictionary, Err)期待した結果と実際の結果を比較する、テスト用の機能です。
Entry for small test helpers that collect asserts.
SQLiteとPostgreSQLを共通のAPIで扱います。処理の完了を待つ間も、ほかのGDScriptは動き続けます。_async付きの関数はGDTaskを返し、あとからawaitで結果を受け取れます。
Database entry shared by SQLite and PostgreSQL. Synchronous-looking calls suspend only their GDScript; *_async returns a GDTask for composition.
sqlite: GD.database.sqlitepostgres: GD.database.postgresredis: GD.database.redisオンラインゲームのマッチング先を管理します。ゲームの同期とゲスト認証はgd-godotのOnlineとSecretで行います。
Manage matchmaking destinations for online games. Online and Secret in gd-godot handle game synchronization and guest authentication.
match(opts: Dictionary = { }) -> GDOnlineMatch, ErrTCPまたはTLSの接続です。読み取りと書き込みはそれぞれ受付順に進みます。タイムアウトを設定でき、close()を呼ぶと待機中の処理も終了します。
Concurrency-safe TCP or TLS byte stream with FIFO reads and writes, deadlines, Close wakeups, and addresses.
read(max: int = 65536) -> PackedByteArray, Errread_async(max: int = 65536) -> GDTask (await PackedByteArray, Err)write(data: PackedByteArray) -> int, Errwrite_async(data: PackedByteArray) -> GDTask (await int, Err)start_tls(host: String, opts: Dictionary = { }) -> GDTCPConn, Errstart_tls_async(host: String, opts: Dictionary = { }) -> GDTask (await GDTCPConn, Err)set_deadline(seconds: float) -> Errset_read_deadline(seconds: float) -> Errset_write_deadline(seconds: float) -> Errlocal_addr() -> Dictionaryremote_addr() -> Dictionaryconnection_state() -> Dictionaryis_open() -> boolclose() -> voidTCP接続を待ち受けます。待ち時間を制限でき、close()を呼ぶと受付待ちの処理も終了します。
TCP listener with deadlines and Close wakeups for pending accepts.
UDPのパケットを送受信します。パケットの区切りと送信元アドレスを保持します。待ち時間を制限でき、close()を呼ぶと待機中の処理も終了します。
UDP endpoint preserving packet boundaries and source addresses, with deadlines and Close wakeups.
read_from(max: int = 65536) -> Dictionary, Errread_from_async(max: int = 65536) -> GDTask (await Dictionary, Err)write_to(data: PackedByteArray, host: String, port: int) -> int, Errwrite_to_async(data: PackedByteArray, host: String, port: int) -> GDTask (await int, Err)set_deadline(seconds: float) -> Errset_read_deadline(seconds: float) -> Errset_write_deadline(seconds: float) -> Erraddr() -> Dictionaryis_open() -> boolclose() -> voidMIMEメディアタイプ、encoded-word、quoted-printable、multipartの読書きを扱います。
Parse and format MIME media types, encoded words, quoted-printable bytes, and multipart bodies.
parse_media_type(text: String) -> Dictionary, Errformat_media_type(type: String, params: Dictionary) -> String, Errencode_word(text: String, mode: String = "b") -> String, Errdecode_word(text: String) -> String, Errdecode_header(text: String) -> String, Errquoted_printable_encode(data: PackedByteArray) -> PackedByteArray, Errquoted_printable_decode(data: PackedByteArray) -> PackedByteArray, Errquoted_printable_reader(source: Variant) -> Variant, Errquoted_printable_writer(sink: Variant) -> Variant, Errmultipart_reader(data: PackedByteArray, boundary: String) -> Variant, Errmultipart_writer(boundary: String = "") -> Variant, Errmultipart_reader_stream(source: Variant, boundary: String) -> Variant, Errmultipart_writer_to(sink: Variant, boundary: String = "") -> Variant, Err解析したメールのヘッダーと本文を保持します。本文はバイト列または逐次読取用のstreamです。
Hold parsed mail headers and a body represented by bytes or a readable stream.
headers: Dictionarybody: VariantSMTP接続を再利用し、挨拶、認証、宛先指定、DATA送信、接続終了を順に行います。
Reuse one SMTP session for greeting, authentication, recipients, DATA transfer, and shutdown.
hello(name: String = "localhost") -> Dictionary, Errhello_async(name: String = "localhost") -> GDTask (await Dictionary, Err)start_tls(opts: Dictionary = { }) -> Dictionary, Errstart_tls_async(opts: Dictionary = { }) -> GDTask (await Dictionary, Err)auth(config: Dictionary) -> Dictionary, Errauth_async(config: Dictionary) -> GDTask (await Dictionary, Err)mail(from: String) -> Dictionary, Errmail_async(from: String) -> GDTask (await Dictionary, Err)rcpt(to: String) -> Dictionary, Errrcpt_async(to: String) -> GDTask (await Dictionary, Err)data() -> GDSMTPDataWriter, Errdata_async() -> GDTask (await GDSMTPDataWriter, Err)reset() -> Dictionary, Errreset_async() -> GDTask (await Dictionary, Err)noop() -> Dictionary, Errnoop_async() -> GDTask (await Dictionary, Err)verify(address: String) -> Dictionary, Errverify_async(address: String) -> GDTask (await Dictionary, Err)quit() -> Dictionary, Errquit_async() -> GDTask (await Dictionary, Err)close() -> voidextension(name: String) -> Dictionarytls_state() -> Dictionaryファイルを少しずつ読み書きするオブジェクトです。同じファイルストリームへの操作は受付順に進み、別のストリームは並行して処理できます。使い終わったらclose()で閉じます。
Reader, Writer, and Closer for ordered incremental access to a regular file. Separate streams proceed concurrently.
read(max: int = 32768) -> PackedByteArray, Errread_async(max: int = 32768) -> GDTask (await PackedByteArray, Err)write(data: PackedByteArray) -> int, Errwrite_async(data: PackedByteArray) -> GDTask (await int, Err)seek(offset: int) -> Variant, Errseek_async(offset: int) -> GDTask (await Variant, Err)close() -> Variant, Errclose_async() -> GDTask (await Variant, Err)is_open() -> bool64ビット整数のビット数の計算、回転、反転、桁上がり付きの演算を行います。
Integer math entry for uint64 bit counts, rotations, reversals, and operations with carry.
len64(x: int) -> intleading_zeros64(x: int) -> inttrailing_zeros64(x: int) -> intones_count64(x: int) -> introtate_left64(x: int, k: int) -> intreverse64(x: int) -> intreverse_bytes64(x: int) -> intadd64(x: int, y: int, carry: int) -> Arraysub64(x: int, y: int, borrow: int) -> Arraymul64(x: int, y: int) -> ArraySMTP DATAの本文を順に書き込み、closeでサーバーの最終応答を受け取ります。
Write an SMTP DATA body in order and receive the server's final response on close.
組み込みのSQLiteへ直接接続する、同期処理用のAPIです。
Entry for opening low-level synchronous connections to embedded SQLite databases.
PostgreSQLの接続と、接続を再利用するプールを作ります。
Entry for creating PostgreSQL clients and connection pools.
Redisの接続と、接続を再利用するプールを作ります。
Entry for creating Redis clients and connection pools.
失敗の種類、説明、追加情報、原因、部分結果を持つ値です。Err.NOT_FOUNDなどは共有値で、直接返せます。独立した失敗はjoin()でまとめ、原因に同じ種類があるかはfind()で調べます。
A failure value with a category, message, details, causes, and partial result. Err.NOT_FOUND and related names are shared values. join() retains independent failures, and find() searches every cause.
msg: Stringkind: Errinfo: Dictionarycause: Errcauses: Arraypartial: Variantnot_found(msg: String = "") -> Errpermission_denied(msg: String = "") -> Erralready_exists(msg: String = "") -> Errinvalid_data(msg: String = "") -> Errtimed_out(msg: String = "") -> Errinterrupted(msg: String = "") -> Errunsupported(msg: String = "") -> Errunauthenticated(msg: String = "") -> Errlimited(msg: String = "") -> Errfrom(reason: Variant, kind: Err = null) -> Errjoin(errors: Array) -> Erras_kind(kind: Err) -> Errnote(msg: String, info: Dictionary = { }) -> Errwith_partial(value: Variant) -> Errfind(target: Variant, where: Dictionary = { }) -> Errtext() -> Stringname_of(kind: Err) -> Stringnames() -> PackedStringArrayERROR: ErrNOT_FOUND: ErrPERMISSION_DENIED: ErrALREADY_EXISTS: ErrINVALID_DATA: ErrTIMED_OUT: ErrINTERRUPTED: ErrUNSUPPORTED: ErrUNAUTHENTICATED: ErrLIMITED: Errテストの実行件数と失敗を集計し、終了コードを返します。
Checker collecting assert counts and failures and producing the test exit code.
failures: intcount: inteq(got: Variant, want: Variant, label: String = "") -> voidne(got: Variant, other: Variant, label: String = "") -> voidok(cond: bool, label: String = "") -> voidno(cond: bool, label: String = "") -> voidnear(got: float, want: float, slack: float = 0.000000001, label: String = "") -> voidhas(box: Variant, item: Variant, label: String = "") -> voidsucceeds(error: Err, label: String = "") -> voidfails(error: Err, kind: Err = null, label: String = "") -> voidcode() -> intreport() -> void処理のキャンセルや制限時間を管理するオブジェクトです。親から子へ、最初のキャンセル理由と期限を伝えます。
Context passing the first cancellation reason and deadline from parent to child.
reason: Err開始した処理の結果を保持するオブジェクトです。ほかの処理を待った後でも、await、GD.async.all()、cancel()、finishedで結果を受け取れます。
Handle to a started operation. It keeps the result, so await, GD.async.all(), cancel() and finished still work after other waits.
コマンドラインのオプションを型に合わせて読み取り、オプション以外の引数も集めます。真偽値はtrue/falseや1/0、整数は0x・0o・0bで始まる表記も使えます。
Parser reading typed bool flags such as true/false and 1/0, integers with 0x, 0o, and 0b prefixes, and collecting positional arguments.
set_name(name: String) -> voidflag_bool(name: String, fallback: bool, help: String = "") -> voidflag_str(name: String, fallback: String, help: String = "") -> voidflag_int(name: String, fallback: int, help: String = "") -> voidparse(args: Array) -> Variant, Errget_bool(name: String) -> boolget_str(name: String) -> Stringget_int(name: String) -> intget_rest() -> PackedStringArrayusage() -> StringファイルやHTTPレスポンスの本文を少しずつ読み書きする型の共通の基底クラスです。通常はGDFileStream、GDWebWriter、GDGzipWriterを使います。
Public base for incrementally supplying file and HTTP response bodies. Users normally work with it as GDFileStream, GDWebWriter, or GDGzipWriter.
HTTP通信を直接扱うサーバーです。HTTP/1のリクエストにはHTTP/1.1で応答し、TLSでHTTP/2を選んだ場合は、各リクエストを独立したストリームで処理します。
Low-level server using HTTP/1.1 responses for HTTP/1 requests and independent streams for TLS-negotiated HTTP/2 requests.
body_limit(bytes: int) -> voidheader_limits(bytes: int, values: int) -> voidlisten(port: int, host: String = "127.0.0.1") -> Variant, Errport() -> intstop() -> voidis_listening() -> boolpoll() -> PackedInt32Arrayget_method(id: int) -> Stringget_path(id: int) -> Stringget_query(id: int) -> Stringget_header(id: int, name: String) -> Stringget_headers(id: int) -> Dictionaryread_body(id: int, bytes: int = 32768) -> Dictionaryrespond(id: int, status: int, body: PackedByteArray, content_type: String = "text/plain; charset=utf-8") -> voidrespond_with(id: int, status: int, headers: Dictionary, body: PackedByteArray) -> voidconnection_count() -> intdropped_headers() -> intGD.web.streamに渡した関数が受け取る出力先です。write(data, offset=0, count=-1)は指定範囲のバイト列を送り、受け付けたバイト数を返します。write_text(text, offset=0, count=-1)は指定範囲の文字列をUTF-8に変換して送ります。count=-1は残りすべてです。送信先が受け取れない間は待ちます。flushは、それまでに書き込んだデータの送信完了を待ちます。切断はflushのエラーやリクエストのキャンセルで確認できます。
The byte destination passed to a GD.web.stream producer. write(data, offset=0, count=-1) sends a range and returns accepted bytes, waiting while the connection is backed up. write_text(text, offset=0, count=-1) sends a character range as UTF-8. count=-1 selects the remainder. flush waits until preceding writes are sent. Detect disconnects through flush errors and request-context cancellation.
write(data: PackedByteArray, offset: int = 0, count: int = -1) -> int, Errwrite_async(data: PackedByteArray, offset: int = 0, count: int = -1) -> GDTask (await int, Err)write_text(text: String, offset: int = 0, count: int = -1) -> int, Errwrite_text_async(text: String, offset: int = 0, count: int = -1) -> GDTask (await int, Err)flush() -> int, Errflush_async() -> GDTask (await int, Err)データを少しずつgzip圧縮し、ファイルや接続、HTTPレスポンスへ出力します。writeは受け付けた入力バイト数を返し、flushは途中までのデータを出力し、closeは圧縮を完了します。操作は受付順に行い、エラーはresetまで残ります。呼び出した処理だけが完了を待ちます。GDTaskを受け取ってあとで待つ場合は_async付きの関数を使います。
Incremental gzip output to files, connections, or HTTP response Writers. write returns the accepted input-byte count; flush publishes buffered output; close completes the member; reset discards state and clears errors. Operations are ordered; failures remain sticky until reset. Methods suspend only the calling routine, with explicit _async variants for signals.
header: Dictionaryset_header(header: Dictionary) -> voidwrite(data: PackedByteArray) -> int, Errwrite_async(data: PackedByteArray) -> GDTask (await int, Err)flush() -> Variant, Errflush_async() -> GDTask (await Variant, Err)close() -> Variant, Errclose_async() -> GDTask (await Variant, Err)reset(writer: RefCounted) -> Variant, Errreset_async(writer: RefCounted) -> GDTask (await Variant, Err)リクエストを処理する関数が受け取るHTTPリクエストです。JSONの解析、キャンセルの管理、大きな本文を少しずつ保存する機能を持ちます。
The HTTP request received by a route handler, with strict JSON, a per-request context, and streaming of large bodies.
context: GDAsyncContextmethod: Stringpath: Stringip: Stringquery: Dictionaryquery_all: Dictionaryparams: Dictionarytarget: Stringheader(name: String) -> Stringheaders() -> Dictionaryread(bytes: int = 32768) -> PackedByteArray, Errbytes() -> PackedByteArray, Errbody_size() -> intlimit(bytes: int) -> Errsave(path: String) -> int, Errtext() -> String, Errjson() -> Variant, Errread_async(bytes: int = 32768) -> GDTask (await PackedByteArray, Err)bytes_async() -> GDTask (await PackedByteArray, Err)save_async(path: String) -> GDTask (await int, Err)text_async() -> GDTask (await String, Err)json_async() -> GDTask (await Variant, Err)keep(name: String, value: Variant) -> voidkept(name: String, fallback: Variant = null) -> Variantvalid(name: String, fallback: Variant = null) -> Variantリクエスト処理の前に入力を検査・加工するミドルウェアの基底クラスです。自作する場合は関数か、handle(req)を持つオブジェクトを渡します。
Base of middleware that inspects and reshapes a request before the handler. To write your own, pass a function or an object with handle(req).
CookieのIDに対応するセッション情報を、有効期限付きで保存します。保存先はこのプロセス内です。
In-process store of expiring sessions keyed by cookie ID.
URLごとの処理、静的ファイル、ミドルウェアを登録して、リクエストを待ち受けるWebアプリケーションです。
Web application that listens with routes, static files, and middleware together.
設定Settings: jobs job_timeout header_timeout body_timeout header_bytes header_values
route(method: String, pattern: String, handler: Callable, middleware: Array = []) -> voidpre(middleware: Variant) -> voiduse(middleware: Variant) -> voidafter(handler: Callable) -> voidon_error(handler: Callable) -> voidshow_errors(on: bool) -> voidbody_limit(bytes: int) -> voidlimits(opts: Dictionary) -> voiddropped_headers() -> intgroup(prefix: String, middleware: Array = []) -> GDWebRouteGroupstatic(prefix: String, dir: String) -> voidfallback(handler: Callable) -> voidfile_at(path: String) -> GDWebResponse, Errfile_at_async(path: String) -> GDTask (await GDWebResponse, Err)listen(port: int, host: String = "127.0.0.1") -> Variant, Errlisten_tls(port: int, cert: String, key: String, host: String = "127.0.0.1", opts: Dictionary = { }) -> Variant, Errlisten_tls_async(port: int, cert: String, key: String, host: String = "127.0.0.1", opts: Dictionary = { }) -> GDTask (await Variant, Err)port() -> intshutdown(context: GDAsyncContext) -> Variant, Errshutdown_async(context: GDAsyncContext) -> GDTask (await Variant, Err)stop() -> voidis_listening() -> boolserve_error() -> Errpoll() -> voidURLの共通部分とミドルウェアをまとめて設定できる、ルートのグループです。
Route group sharing a prefix and middleware.
受信したHTTPステータスコード、ヘッダー、本文を持つオブジェクトです。本文をJSONとして解析すると、値とErrを返します。
Response holding the received HTTP status, headers, and body, returning strict JSON as a value and Err.
status: intheaders: Dictionarybody: PackedByteArrayGD.html.templateで解析したテンプレートです。executeは文字列、execute_bytesはUTF-8のバイト列を生成します。解析結果は変更されないため、複数のリクエストで共有できます。
Immutable template parsed by GD.html.template. execute renders text, execute_bytes renders UTF-8 bytes, and the value can be shared across requests.
ゲーム名ごとに部屋と身元確認サーバーの場所を記録し、参加先を返すエンドポイントです。ゲームの通信内容は中継しません。
Directory that records rooms and identity gateways per game and returns a destination. It does not relay game traffic.
handle(req: GDWebRequest) -> GDWebResponse, Errlisten(port: int, host: String = "127.0.0.1") -> Variant, Errport() -> intstop() -> void1つのPostgreSQL接続を操作します。通常の関数は呼び出した処理だけを待たせ、_async付きの関数はGDTaskを返します。
Client for one PostgreSQL connection. Regular methods suspend only their caller; *_async returns a GDTask for concurrent composition.
設定Settings: user database password connect_timeout timeout auth allow_cleartext_password tls ca
open(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }) -> Variant, Errquery(sql: String, args: Array = []) -> Dictionary, Errquery_row(sql: String, args: Array = [], max_bytes: int = 0) -> Dictionary, Errquery_rows(sql: String, args: Array = []) -> GDDatabaseRows, Errquery_values(sql: String, args: Array = []) -> Dictionary, Errquery_flat(sql: String, args: Array = []) -> Dictionary, Errquery_many(sql: String, rows: Array) -> Array, Errfetch_many(sql: String, rows: Array) -> Array, Errfetch_values_many(sql: String, rows: Array) -> Array, Errfetch_flat_many(sql: String, rows: Array) -> Array, Errexec_many(sql: String, rows: Array) -> int, Erropen_async(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }) -> GDTask (await Variant, Err)query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_row_async(sql: String, args: Array = [], max_bytes: int = 0) -> GDTask (await Dictionary, Err)query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)query_values_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_flat_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_values_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_flat_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)exec_many_async(sql: String, rows: Array) -> GDTask (await int, Err)is_open() -> boolclose() -> voidcheck(sql: String) -> Variant, Errcheck_async(sql: String) -> GDTask (await Variant, Err)in_flight() -> intcached_stmts() -> intPostgreSQL接続を必要に応じて上限まで作り、複数の処理で再利用します。空き接続の待機と、接続状況の確認ができます。
Concurrency-safe pool opening PostgreSQL connections on demand up to a maximum, with a wait queue and connection statistics.
open(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }, size: int = 0) -> Variant, Errquery(sql: String, args: Array = []) -> Dictionary, Errquery_row(sql: String, args: Array = [], max_bytes: int = 0) -> Dictionary, Errquery_rows(sql: String, args: Array = []) -> GDDatabaseRows, Errquery_values(sql: String, args: Array = []) -> Dictionary, Errquery_flat(sql: String, args: Array = []) -> Dictionary, Errquery_many(sql: String, rows: Array) -> Array, Errfetch_many(sql: String, rows: Array) -> Array, Errfetch_values_many(sql: String, rows: Array) -> Array, Errfetch_flat_many(sql: String, rows: Array) -> Array, Errexec_many(sql: String, rows: Array) -> int, Erropen_async(host: String = "127.0.0.1", port: int = 5432, opts: Dictionary = { }, size: int = 0) -> GDTask (await Variant, Err)query_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_row_async(sql: String, args: Array = [], max_bytes: int = 0) -> GDTask (await Dictionary, Err)query_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)query_values_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_flat_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_values_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)fetch_flat_many_async(sql: String, rows: Array) -> GDTask (await Array, Err)exec_many_async(sql: String, rows: Array) -> GDTask (await int, Err)close() -> voidsize() -> intin_flight() -> intstats() -> DictionarySQLiteとPostgreSQLに共通する、SQLの実行、1行ずつの読み取り、先頭行の取得、接続状況の確認に使います。
Client providing shared SQLite and PostgreSQL queries, streaming Rows, first-row lookup, and connection statistics.
設定Settings: driver path host port max_rows max_bytes
open(opts: Dictionary) -> Variant, Erropen_async(opts: Dictionary) -> GDTask (await Variant, Err)query(sql: String, args: Array = []) -> Dictionary, Errquery_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_row(sql: String, args: Array = []) -> Dictionary, Errquery_row_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Errquery_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)transaction(action: Callable) -> Variant, Errtransaction_async(action: Callable) -> GDTask (await Variant, Err)serialize(action: Callable) -> Variant, Errserialize_async(action: Callable) -> GDTask (await Variant, Err)migrate(statements: Array) -> int, Errmigrate_async(statements: Array) -> GDTask (await int, Err)stats() -> Dictionaryclose() -> voidis_open() -> boolトランザクションが終わるまで専用の接続を使うデータベースクライアントです。
Dedicated client holding one physical connection until the transaction ends.
query(sql: String, args: Array = []) -> Dictionary, Errquery_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_row(sql: String, args: Array = []) -> Dictionary, Errquery_row_async(sql: String, args: Array = []) -> GDTask (await Dictionary, Err)query_rows(sql: String, args: Array = []) -> GDDatabaseRows, Errquery_rows_async(sql: String, args: Array = []) -> GDTask (await GDDatabaseRows, Err)is_active() -> bool1つのRedis接続を操作します。通常の関数は呼び出した処理だけを待たせ、_async付きの関数はGDTaskを返します。
Client for one Redis connection. Regular methods suspend only their caller; *_async returns a GDTask for concurrent composition.
設定Settings: password timeout tls ca
open(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }) -> Variant, Errquery(cmd: String, args: Array = []) -> Variant, Errpipeline(cmds: Array) -> Array, Errtransaction(cmds: Array) -> Array, Errsubscribe(channels: PackedStringArray) -> Variant, Erropen_async(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }) -> GDTask (await Variant, Err)query_async(cmd: String, args: Array = []) -> GDTask (await Variant, Err)pipeline_async(cmds: Array) -> GDTask (await Array, Err)transaction_async(cmds: Array) -> GDTask (await Array, Err)subscribe_async(channels: PackedStringArray) -> GDTask (await Variant, Err)is_open() -> boolis_subscribed() -> boolin_flight() -> intclose() -> void複数のRedis接続へ処理を割り振り、同時に利用できるようにします。
Concurrency-safe pool distributing work across several Redis connections.
open(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }, size: int = 0) -> Variant, Errquery(cmd: String, args: Array = []) -> Variant, Erropen_async(host: String = "127.0.0.1", port: int = 6379, opts: Dictionary = { }, size: int = 0) -> GDTask (await Variant, Err)query_async(cmd: String, args: Array = []) -> GDTask (await Variant, Err)close() -> voidsize() -> intin_flight() -> int組み込みSQLiteへの同期接続です。
Synchronous connection to the embedded SQLite.
一度prepareで解析し、値を変えて繰り返し実行できるSQLiteのSQL文です。
A SQLite statement prepared once and reused.
run(params: Array = []) -> Dictionary, Errrun_many(rows: Array) -> Dictionary, Errone(params: Array = []) -> Variant, Errall(params: Array = []) -> Array, Errclose() -> voidis_valid() -> bool分割して届くJSON Linesのデータを、1行ずつ読み取ります。
Reader decoding JSON Lines one line at a time as chunks arrive.
pickで求めた値が小さい要素から取り出すヒープです。
Heap that pops the value with the smallest rank chosen by pick first.
priorityの値が小さい順に取り出すキューです。同じ値なら、追加した順に取り出します。
Queue that pops the smallest priority number first, and insertion order among equals.
最近使った値を、件数と有効期限を指定して保存するキャッシュです。必要な値がなければ作成して返せます。
Cache holding recently used values under a count and expiry limit, creating a value when missing.
setup(limit: int, ttl_ms: int = 0) -> voidput(key: Variant, value: Variant) -> voidtake(key: Variant, fallback: Variant = null) -> Variantfetch(key: Variant, make: Callable) -> Varianthas(key: Variant) -> boolerase(key: Variant) -> voidclear() -> voidsize() -> intlimit() -> inthit_count() -> intmiss_count() -> inthit_rate() -> float関数の引数と結果をキャッシュに保存し、同じ引数で呼ばれたときに結果を再利用します。長く使われていない項目から削除するLRU方式です。
Wrapper remembering a function's arguments and results in an LRU cache.
GD.web.text、html、json、bytes、streamなどが返すHTTPレスポンスです。statusとbodyを変更でき、typeからContent-Typeを読めます。headersには追加ヘッダーとContent-Typeが入ります。ヘッダーの追加にはGD.web.headerを使います。
The HTTP response returned by GD.web.text, html, json, bytes, and stream. Its status and body can be changed, while type exposes Content-Type. The headers property includes extra fields and Content-Type; use GD.web.header to add a field.
status: intbody: Variantheaders: Dictionarytype: String結果を1行ずつ読み取るオブジェクトです。next()で次の行に進み、scan()またはvalues()でその行の値を取得します。読み取り後はerr()でエラーを確認し、close()で閉じます。
Incremental query results. Advance with next(), decode the current row with scan() or values(), inspect err(), and release resources with close().