LoginSignup
7
3

More than 1 year has passed since last update.

Phoenix[Elixir]を使ってNeosVR用のAPIを最短で作ってみる

Posted at

動作環境

$ cat /etc/os-release | grep VERSION=
VERSION="20.04.4 LTS (Focal Fossa)"

$ elixir -v
Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [jit]

Elixir 1.13.0 (compiled with Erlang/OTP 24)

$ mix phx.new --version
Phoenix installer v1.6.7

プロジェクトの作成

今回はDBを使わないため--no--ectoを指定します

$ mix phx.new neoex --no-ecto

* creating neoex/config/config.exs
    省略
* creating neoex/priv/static/favicon.ico

Fetch and install dependencies? [Yn] Y
* running mix deps.get
* running mix deps.compile

We are almost there! The following steps are missing:

    $ cd neoex

Start your Phoenix app with:

    $ mix phx.server

You can also run your app inside IEx (Interactive Elixir) as:

    $ iex -S mix phx.server

Phoenixの起動

$ cd neoex
$ phx.server
Compiling 13 files (.ex)
Generated neoex app
[info] Running NeoexWeb.Endpoint with cowboy 2.9.0 at 127.0.0.1:4000 (http)
[debug] Downloading esbuild from https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.29.tgz
[info] Access NeoexWeb.Endpoint at http://localhost:4000
[watch] build finished, watching for changes...

ブラウザで起動確認

http://localhost:4000にアクセスします
Screenshot from 2022-05-26 14-14-22.png

APIを作ろう

lib/neoex_web/router.exを編集
/exec/値のパス追加します

 defmodule NeoexWeb.Router do
   use NeoexWeb, :router

   #省略
   scope "/", NeoexWeb do
     pipe_through :browser

+    get "/exec/:val", PageController, :exec
     get "/", PageController, :index
   end
  
   #省略
end

lib/neoex_web/views/page_view.exを編集
プレーンテキストを表示できるようにrender関数を追加します

 defmodule NeoexWeb.PageView do
   use NeoexWeb, :view

+  def render("exec.txt", %{val: val}) do
+    val
+  end
 end

lib/neoex_web/controllers/page_controller.exを編集

exec関数を追加します
router.exで指定した:execと同じ名前にします

 defmodule NeoexWeb.PageController do
   use NeoexWeb, :controller

   def index(conn, _params) do
     render(conn, "index.html")
   end

+  def exec(conn, params) do
+    val = """
+    あなたの名前は#{params["val"]}です
+    """
+    render(conn, "exec.txt", val: val)
+  end
 end

ブラウザで動作確認

http://localhost:4000/exec/hoge

Screenshot from 2022-05-26 14-01-35.png

NeosVR側

NeosVRで下記のLogiXを作ってPulseを押します

Screenshot from 2022-05-26 14-05-43.png
これで完成です

試しにhogeをabcに書き換えます
http://localhost:4000/exec/abc
Screenshot from 2022-05-26 14-07-31.png

表示結果が変化することを確認できました

7
3
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
7
3