GoではじめるWebAssebmly その3「GET系ネットワーク処理」
WebAssebmlyはWebブラウザ上でバイナリファイル(テキスト形式もあり)を実行できる環境です。JavaScriptと異なりコードの漏洩がなく、実行速度も高速というのがメリットです。
WebAssebmlyは元々Rustで開発することが多かったですが、最近では様々なプログラミング言語が対応しています。その一つがGoです。Go 1.11からWebAssembly向けにもコンパイルできるようになっています。
一般的なWebAssemblyはDOMやネットワーク操作が行えません。それに対してGo 1.11ではJavaScript APIを使えるようにした syscall/js
パッケージを用いることで、DOMやネットワーク操作を可能にしています。
そこで今回はネットワーク処理(GET処理)の書き方を解説します。
使いどころ
GET処理の使いどころはもちろん、Web APIからのデータ取得になるはずです。今回は文字列が配列で返ってくるケースを紹介します。
JSONを利用するためには構造体を定義する必要あり
Goの若干面倒な部分として、JSONを利用するためには構造体を定義する必要があるという点があげられます。例えば以下のような形です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Todos struct { | |
Array []string | |
} |
ネットワークは net/http で行う
Goでネットワーク処理を記述する場合には net/http
ライブラリを使います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"net/http" | |
"bytes" | |
) |
処理について
例えばあるドメイン domain
からJSON文字列を取得するデモコードです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getTodos(domain string) ([]string, error) { | |
// 構造体の定義 | |
var todos []string | |
// HTTPリクエスト | |
res, err := http.Get(domain) | |
// エラー処理 | |
if err != nil { | |
return todos, err | |
} | |
// HTTPセッションのクローズ | |
defer res.Body.Close() | |
// レスポンスボディの読み込み | |
body, err := ioutil.ReadAll(res.Body) | |
// エラー処理 | |
if err != nil { | |
return todos, err | |
} | |
// JSONを文字列の配列に変換 | |
err = json.Unmarshal([]byte(body), &todos) | |
// 返却 | |
return todos, err | |
} |
後はこの関数を実行します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
todos, err := getTodos(domain) |
これでJSONの取得とパースが完了します。なお、見ての通り、このコードはネットワーク部分を同期的に処理しています。関数の頭に go をつけることで非同期処理になりますが、描画部分を考えると同期(または描画を含めて非同期)処理にしなければなりません。
また、このネットワーク接続はWebAssemblyの中で行われているのではなく、メインスレッド側で行われます。そのため開発者ツールなどでリクエスト内容は確認できます。ネットワーク接続を秘匿にするのは困難なので、注意してください。
コメントは受け付けていません。