簡易Webサーバーを言語別で起動してみる
March 31, 2020
この記事は1年以上が経過しています。内容が古い可能性があります。
目次
やりたいこと
静的ファイル/ディレクトリを表示する簡易Webサーバーを立てたい
言語は
- Node.js
- Go
- Python
で試してみる
Node.js
ライブラリ connect vs express vs fastify vs koa vs http-server vs restify | npm trends
http-server vs static-server vs serve vs lite-server vs live-server | npm trends
- http-server
- http(Node.js標準): https://nodejs.org/ja/about/
- express
- koa
- connect
- serve
など
express
がメジャーだが、簡易Webサーバーとして219kb
と大きい。
また、機能が豊富過ぎる
一番簡単なのは、http-server
http-server
http-server -p 9000 public
デーモン化は、pm2
を使用するのがいいだろう
pm2のインストール
yarn add pm2
// or
npm install pm2
// 起動
pm2 start {ファイル}
で起動する
shellにするにして起動する場合、
start.sh
#!bin/sh
http-server -p 9000 public
として、
pm2 start start.sh
で実行可能
もしくは、Node.jsからコマンド実行(child_process
)を使用する
app.js
const { exec } = require('child_process')
exec('http-server -p 9000 public', (err, stdout, stderr) => {
if (err) {
console.log(`stderr: ${stderr}`)
return
}
console.log(`stdout: ${stdout}`)
}
)
serve
Static file serving and directory listing
とあるように静的ファイルサーバーに最適 コマンド・ミドルウェア起動にも対応
インストール
yarn add serve
コマンド起動
serve {ディレクトリパス}
// e.g.
serve public
middlewareをして起動する
serve.js
const handler = require('serve-handler')
const http = require('http')
const server = http.createServer((request, response) => {
handler.public('public')
return handler(request, response)
// or
// return handler(request, response , {
// public: 'public'
// })
})
server.listen(9000, () => {
console.log('Running at http://localhost:9000')
})
pm2 start serve.js
Go
標準ライブラリのnet/http
のみで実装可能
構成
├── main.go
└── public
└── index.html
main.go
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
fmt.Println("start... http://localhost:8080")
http.Handle("/", http.StripPrefix("/",
http.FileServer(http.Dir("./public/"))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
起動
go run main.go
ビルドして起動
go build -o server main.go
./server
Python
コマンドで実行する
// 3系
python -m http.server 8000
// 2.7系
python -m SimpleHTTPServer 8000
スクリプトで実行する
├── .python-version
├── index.html
└── server.py
.python-version
3.6.1
index.html
<html>
<body>
Hello!
</body>
</html>
server.py
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
以下コマンドで実行する
python server.py