0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Oracle Linux で WebAssembly(Wasm)を動かしてみた 〜Go編〜

0
Posted at

はじめに

Oracle Linux 上で Go を使って WebAssembly(Wasm)を動かしてみました。
環境構築からビルド・実行まで、ステップごとに解説します。

環境

  • Oracle Linux 9
  • Go(これから入れます)
  • Wasmtime(これからバッチリ入れます)

① Go のインストール

GoでWasmを試すフォルダを作ります。
image.png
(!急募:フォルダの命名センス!)

Oracle Linux は RHEL 互換なので、dnf で一発インストールできます。

sudo dnf install golang -y

確認:

$ go version
go version go1.25.7 (Red Hat 1.25.7-1.el9_7) linux/amd64

1コマンドでGoのインストール終了なんて、RedHatに感謝しかないですね!

② Wasmtime のインストール

Wasmtime は Go でビルドした .wasm ファイルを実行するためのランタイムです。

curl https://wasmtime.dev/install.sh -sSf | bash

以下のような出力が出ればOKです。

Editing user profile (/home/opc/.bashrc)
Finished installation. Open a new terminal to start using Wasmtime!

新しいターミナルを開くと PATH が自動で通りますが、今すぐ使いたい場合は手動で通します(私はPATHを通す派です)

export PATH="$HOME/.wasmtime/bin:$PATH"

確認:

$ wasmtime --version
wasmtime 42.0.0 (aa3cfe72f 2026-02-24)

③ Go コードを書く

作業ディレクトリを作成してファイルを編集します。

mkdir Gowasm && cd Gowasm
nano main.go

まずはシンプルな Hello World から:

package main

import "fmt"

func main() {
    fmt.Println("Hello from Go WASM!")
}

④ Wasm 向けにビルドする

通常の go build とは少し異なるビルドコマンドを使います:

GOOS=wasip1 GOARCH=wasm go build -o main.wasm main.go

コマンドの解説

オプション 意味
GOOS=wasip1 OS のターゲットを WASI Preview1 に指定(Linux/Windows/macOS ではなく WASI 用)
GOARCH=wasm CPU アーキテクチャを WebAssembly に指定(amd64/arm64 ではなく Wasm 形式で出力)
go build コンパイル(翻訳)コマンド
-o main.wasm 出力ファイル名を main.wasm に指定
main.go コンパイル対象のソースファイル

.wasmファイルができました!

image.png

⑤ 実行してみる

$ wasmtime main.wasm
Hello from Go WASM!

動きました!!Wasmtimeの絶対時間!

⑥ ファイル読み込みも試してみる

Wasm はサンドボックス環境で動くため、ファイルシステムへのアクセスには明示的な許可が必要です。

main.go を書き換えます:

package main

import (
    "fmt"
    "os"
)

func main() {
    data, err := os.ReadFile("test.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(data))
}

読み込むファイルを用意:

echo "WASI is cool" > test.txt

ビルド:

GOOS=wasip1 GOARCH=wasm go build -o main.wasm main.go

実行(--dir=. でカレントディレクトリへのアクセスを許可):

$ wasmtime --dir=. main.wasm
WASI is cool

--dir=. が必要な理由

Wasmはデフォルトでファイルシステムに直接アクセスできません。--dir=. を指定することで、カレントディレクトリへの読み書きを明示的に許可します。

まとめ

ステップ コマンド
Go インストール sudo dnf install golang -y
Wasmtime インストール curl https://wasmtime.dev/install.sh -sSf | bash
Wasm ビルド GOOS=wasip1 GOARCH=wasm go build -o main.wasm main.go
実行(基本) wasmtime main.wasm
実行(ファイルアクセスあり) wasmtime --dir=. main.wasm

Oracle Linux + Go + Wasmtime の組み合わせはスムーズに動作しました。
WASI のサンドボックスモデルを意識しながら Wasm を活用していきましょう!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?