: トップ : 差分 : 一覧 : ソース : 検索 : ヘルプ : PDF : ログイン

Mojolicious

最終更新時間:2025年12月05日 01時04分26秒


とりあえず.

$ mojo generate lite-app

css や js など性的ファイルは public フォルダに置く.
プログラムでファイルを作成してダウンロードできるようにするには
そのファイルも public以下に生成させると,<a ref="hoge.csv"> hoge </a> でアクセスできる.
外部テンプレートフォルダは templates で,hoge.html.ep などを置く.

クライアントとして

$ mojo get https://mojolicious.org
$ ./myapp.pl get /foo
$ ./myapp.pl get -M PUT -c '{"message":"Hello Mojo!"}' /hoge

フォームで JSON をやり取りするサンプル

myapp.pl

#!/usr/bin/env perl
use Mojolicious::Lite -signatures;

get '/' => sub ($c) {
  $c->render(template => 'index');
};

get '/form' => sub ($c) {
  $c->render(template => 'form');
};

put '/endpoint' => sub ($c) {
  my $hash = $c->req->json;
  $c->render(json => {n => ++$hash->{num}});
};

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Welcome';
<h1>Welcome to the Mojolicious real-time web framework!</h1>

@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>

templates/form.html.ep

% layout 'default';
% title 'Form Test';

Input number.
<form id="form_x">
   <label for="int">N:</label>
   <input type="text" id="int" name="int" required>
   <button type="submit">Send</button>
</form>

<div id="result"></div>

<script>
document.getElementById("form_x").addEventListener("submit", function(event) {
       event.preventDefault();
       const i = document.getElementById("int").value;
       fetch("/post", {
           method: "POST",
           headers: {
               "Content-Type": "application/json",
           },
           body: JSON.stringify({num: i}),
       })
       .then(response => response.json())
       .then(data => {
           document.getElementById("result").innerHTML = "next number: " + data.n;
       })
       .catch(error => {
           document.getElementById("result").innerHTML = "error: " + error;
       });
});
</script>


FeeBSD用rc

/usr/local/etc/rc.d/mojolicious

#!/bin/sh
#
# PROVIDE: mojolicious
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr

name=mojolicious
rcvar=mojolicious_enable

command="/usr/local/bin/hypnotoad"
myprg="/home/mojolicious/myapp.pl"

start_cmd="${command} ${myprg}"
stop_cmd="${command} -s ${myprg}"

load_rc_config ${name}

run_rc_command "$1"