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?

OCIのOracle LinuxにいれたWebサーバでプログラムを使って値を保持・表示する

0
Posted at

前の記事

OCIのOracle LinuxにいれたWebサーバでプログラム(cgi)を動かす(nginx + cgi[perl])

やってみたいこと

別のブラウザから送られてきた値を別のブラウザで表示する

1.Perlモジュールの変更

新しいperlモジュール
package MyWebScript;
use nginx;

# 保存先ファイルのパス
my $data_file = '/etc/nginx/perl/data.txt';

# --------------------------------------------------
# メインの処理(入力・保存・クリア)
# --------------------------------------------------
sub handler {
    my $r = shift;
    $r->send_http_header("text/html; charset=utf-8");
    my $args_str = $r->args;

    # 1. クリア処理
    if ($args_str && $args_str =~ /clear=1/) {
        if (open(my $fh, '>', $data_file)) { close($fh); }
        $r->print("<html><head><meta http-equiv='refresh' content='1;url=/run-perl'></head><body>");
        $r->print("<h2>データをクリアしました!</h2></body></html>");
        return OK;
    }

    # 2. 保存処理
    my $memo_value = "";
    if ($args_str && $args_str =~ /memo=([^&]+)/) {
        $memo_value = $1;
        $memo_value =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
    }

    if ($memo_value ne "") {
        if (open(my $fh, '>', $data_file)) {
            print $fh $memo_value;
            close($fh);
        }
        $r->print("<html><head><meta http-equiv='refresh' content='1;url=/run-perl'></head><body>");
        $r->print("<h2>データを保存しました!</h2></body></html>");
        return OK;
    }

    # 通常画面表示
    show_page($r);
    return OK;
}

sub show_page {
    my $r = shift;
    my $saved_content = get_file_content();

    $r->print("<html><body>");
    $r->print("<h2>簡易メモ帳 (Nginx + Perl / GET方式)</h2>");
    $r->print('<form method="GET" action="/run-perl" style="display:inline;">');
    $r->print('<input type="text" name="memo" style="width:300px;" placeholder="保存する文字を入力" required> ');
    $r->print('<input type="submit" value="保存">');
    $r->print('</form>');
    $r->print(' <a href="/run-perl?clear=1" style="display:inline-block; padding:3px 10px; background:#f44336; color:white; text-decoration:none; border-radius:3px; font-size:14px; margin-left:10px;">データをクリア</a>');

    # リアルタイム画面へのリンクを新設
    $r->print(' <a href="/view-perl" target="_blank" style="display:inline-block; padding:3px 10px; background:#00bc8c; color:white; text-decoration:none; border-radius:3px; font-size:14px; margin-left:10px;">リアルタイム画面を開く ➔</a>');

    $r->print("<hr><h3>現在保存されている値:</h3>");
    if ($saved_content ne "") {
        $r->print("<pre style='background:#f0f0f0; padding:10px; font-size:16px;'>" . $saved_content . "</pre>");
    } else {
        $r->print("<p style='color:gray;'>まだデータは保存されていません。</p>");
    }
    $r->print("</body></html>");
}

# --------------------------------------------------
# 0.1秒おきに裏側でデータを読み取る超高速モニター画面
# --------------------------------------------------
sub viewer {
    my $r = shift;
    $r->send_http_header("text/html; charset=utf-8");

    $r->print("<html><head><title>リアルタイムモニター</title>");
    $r->print("<script>");
    $r->print("  function updateData() {");
    $r->print("    fetch('/data-perl')"); # 裏でテキストデータを取得
    $r->print("      .then(response => response.text())");
    $r->print("      .then(text => {");
    $r->print("        const box = document.getElementById('data-box');");
    $r->print("        if(text.trim() === '') {");
    $r->print("          box.innerHTML = '<span style=\"color:gray;\">まだデータは保存されていません。</span>';");
    $r->print("        } else {");
    $r->print("          box.textContent = text;");
    $r->print("        }");
    $r->print("      });");
    $r->print("  }");
    $r->print("  setInterval(updateData, 100);"); # 100ミリ秒(0.1秒)おきに実行
    $r->print("  window.onload = updateData;");   # 初回読み込み時にも実行
    $r->print("</script></head>");
    $r->print("<body style='font-family:sans-serif; padding:20px;'>");
    $r->print("<h2>⏱️ リアルタイムデータモニター (0.1秒更新)</h2>");
    $r->print("<p>メイン画面で値が保存されると、この画面が0.1秒以内に自動で書き換わります。</p>");
    $r->print("<hr>");
    $r->print("<pre id='data-box' style='background:#222; color:#0f0; padding:20px; font-size:24px; font-family:monospace; border-radius:5px; min-height:50px;'></pre>");
    $r->print("</body></html>");

    return OK;
}

# --------------------------------------------------
# テキストデータだけをプレーンに返すAPI
# --------------------------------------------------
sub data_api {
    my $r = shift;
    $r->send_http_header("text/plain; charset=utf-8"); # プレーンテキストとして返す
    $r->print(get_file_content());
    return OK;
}

# 共通ファイル読み込み関数
sub get_file_content {
    my $content = "";
    if (open(my $fh, '<', $data_file)) {
        local $/;
        $content = <$fh>;
        close($fh);
    }
    return $content;
}

1;
__END__

2.nginx設定の変更

2.1.cgi設定変更前の動作確認

nginxの設定ファイル確認

変更前

[opc@test-server ~]$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

syntax is ok、test is successfulになって問題なし。

2.2.新しいスクリプト動作のための設定

Perlスクリプト(.pmファイル)配置ディレクトリ設定追加

Perlスクリプト(.pmファイル)配置ディレクトリ設定追加

変更前

[opc@test-server ~]$ cat /etc/nginx/nginx.conf
(省略)
        # Perlスクリプト(.pmファイル)
        location /run-perl {
        #    perl 'sub {
        #        my $r = shift;
        #        $r->send_http_header("text/html; charset=utf-8");
        #        $r->print("Hello from inline Perl script!");
        #        return OK;
        #    }';
             perl MyWebScript::handler;
        }
    }
(省略)

変更:location /run-perl{}の後に、

        # 0.1秒おきに自動更新されるビューアー画面
        location /view-perl {
             perl MyWebScript::viewer;
        }

        # Perlが保存したテキストデータだけを純粋に返すURL
        location /data-perl {
             perl MyWebScript::data_api;
        }

を入れる。

変更後

```shell-session
[opc@test-server ~]$ cat /etc/nginx/nginx.conf
(省略)
        # Perlスクリプト(.pmファイル)
        location /run-perl {
        #    perl 'sub {
        #        my $r = shift;
        #        $r->send_http_header("text/html; charset=utf-8");
        #        $r->print("Hello from inline Perl script!");
        #        return OK;
        #    }';
             perl MyWebScript::handler;
        }

        # 0.1秒おきに自動更新されるビューアー画面
        location /view-perl {
             perl MyWebScript::viewer;
        }

        # Perlが保存したテキストデータだけを純粋に返すURL
        location /data-perl {
             perl MyWebScript::data_api;
        }
    }
(省略)

変更後確認

[opc@test-server ~]$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx再起動

[opc@test-server ~]$ sudo systemctl stop nginx
[opc@test-server ~]$ sudo pkill -9 nginx
[opc@test-server ~]$ sudo systemctl start nginx

※pkill -9は、停止したはずのnginxが残る(ゾンビプロセス)影響を排除するため。

最後に

記事の内容はCC BY-SA 4.0(著作者の情報とCCライセンス継承はお願いします。商用利用・改変・再配布は問題なし)です。

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?