LoginSignup
17
12

More than 5 years have passed since last update.

Lorcaを使ってGoでHTML5アプリを作ろう!

Last updated at Posted at 2018-11-20

2019/02追記

サンプルのリポジトリを追加
https://github.com/gashirar/lorca-sample

はじめに

https://github.com/zserge/lorca
上記の紹介と、サンプルの疎通をしてみます。

Lorcaとは

  • モダンなHTML5デスクトップアプリを作るためのライブラリ
  • UIレイヤはChromeブラウザを利用
    • Electronのようにパッケージにバンドルはしない
    • インストールされたChromeを利用

名前の由来は?
Lorca is an anagram of Carlo, a project with a similar goal for Node.js.
https://github.com/GoogleChromeLabs/carlo/

Getting Started

作るものの概要

JavaScriptからGoの呼び出しと、GoからJavaScriptの呼び出しをやってみます。
動きは下記のようなながれをイメージ。

  1. 画面上のボタンを押す
    • JavaScriptからGoのfunc呼び出し(helloFromGo)
    • GoからJavaScriptのfunction呼び出し(helloFromJavaScript)
    • Goからdocument.getElementByIdを呼び出し
  2. 画面に文字が表示

ソース

package main

import (
    "net/url"

    "github.com/zserge/lorca"
)

var ui lorca.UI

func main() {
    ui, _ = lorca.New("", "", 480, 320)
    defer ui.Close()

  // GoのfuncをJavaScriptで呼び出せるようBind
    ui.Bind("helloFromGo", helloFromGo)

  // 今回はurl.PathEscapeでそのままHTMLを配置
  // ※下記はHTTPサーバをたててそこから取得する例
  //   https://github.com/zserge/lorca/tree/master/examples/counter
    ui.Load("data:text/html," + url.PathEscape(`
    <!doctype html>
    <html lang="ja">
    <head>
    <script>
        function helloFromJavaScript() {
            return 'Hello from JavaScript!'
        }
    </script>
    </head>
    <body>
        <button onclick="helloFromGo()">Hello!</button>
        <div id="content"></div>
    </body>
    </html>
    `))

    <-ui.Done()
}

func helloFromGo() {
  // JavaScriptのfunction呼び出し
    s := ui.Eval(`helloFromJavaScript();`).String() + "<br>" + "Hello From Go!"
  // HTMLに反映
    ui.Eval(`document.getElementById('content').innerHTML="`+s+`";`)
}

実行

go run main.go

クリップボード01.jpg
ボタンを押すと...
クリップボード02.jpg
JavaScriptからGo、GoからJavaScriptの呼び出しができました

所感

上記のように、GoとJavaScriptの双方向呼び出しが簡単にできました。
より詳しい処理を見たい方はexampleを触ってみるのがオススメです!
https://github.com/zserge/lorca/tree/master/examples

2018年11月5日くらいにInitial Commitですが、すでにStar数も1500とぐんぐん伸ばしています。
GoでちょっとしたGUIツールを作るのにつかってみるのはいかがでしょうか。

17
12
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
17
12