deno上で動作するデスクトップアプリを作成してブラウザからファイルの読み書きや各種プログラムの起動などを行えるようにする一方で、ネットワーク接続された他の機器から「http://IPアドレス:ポート番号」で起動中のアプリの画面を開いて操作されるのは防がないと色々危険なので、アクセス元に応じて処理を切り替えるサンプルが以下。
可能な限りサンプルソースを短くしたかったので以下の動作となるようにした。
- ローカルPCからアクセスした場合は404エラーにする。
- 別のPCからアクセスした場合は403エラーにする。
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 { serve } from "https://deno.land/std/http/server.ts"; | |
const port = 8080; | |
const server = serve({ port: port }); | |
const serverURL = `http://127.0.0.1:${port}`; | |
console.log(serverURL); | |
for await (const req of server) { | |
const hostname = (req.conn.remoteAddr as Deno.NetAddr).hostname; | |
console.log(hostname, req.method, req.url); | |
if(hostname != '127.0.0.1'){ | |
req.respond({status:403}) | |
continue | |
} | |
req.respond({status:404}) | |
} |
ローカルホストの場合。
リモートホストの場合。
以下のページを参考にさせて頂きました。
簡易HTTPサーバーでブラウザからファイルの入出力を試す
0 件のコメント:
コメントを投稿