Created
March 25, 2025 09:31
-
-
Save naogify/5754999897194c1c6cb44b4b853e6393 to your computer and use it in GitHub Desktop.
xyzディレクトリ形式のタイルをローカルでホストするスクリプト(gzip/cors対応)
This file contains hidden or 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
| #!/bin/bash | |
| # ==== 設定 ==== | |
| PORT=8000 | |
| DIRECTORY="./tiles" # 配信するディレクトリ(必要に応じて変更) | |
| # 一時ファイルを作成(macOS などの場合) | |
| PYTHON_SERVER=$(mktemp -t pbf_server.py.XXXXXX) | |
| if [ -z "$PYTHON_SERVER" ]; then | |
| echo "一時ファイルの作成に失敗しました" | |
| exit 1 | |
| fi | |
| # サーバー終了時に一時ファイルを削除するように設定 | |
| trap "rm -f $PYTHON_SERVER" EXIT | |
| # Python の HTTP サーバー用コードを一時ファイルに出力 | |
| cat <<'EOF' > "$PYTHON_SERVER" | |
| import http.server | |
| import socketserver | |
| import os | |
| PORT = __PORT__ | |
| DIRECTORY = os.path.abspath("__DIRECTORY__") | |
| class CustomHandler(http.server.SimpleHTTPRequestHandler): | |
| def end_headers(self): | |
| self.send_header("Access-Control-Allow-Origin", "*") | |
| super().end_headers() | |
| def guess_type(self, path): | |
| if path.endswith(".pbf"): | |
| return "application/vnd.mapbox-vector-tile" | |
| return super().guess_type(path) | |
| def send_head(self): | |
| path = self.translate_path(self.path) | |
| f = None | |
| if os.path.isdir(path): | |
| return super().send_head() | |
| ctype = self.guess_type(path) | |
| try: | |
| f = open(path, 'rb') | |
| except OSError: | |
| self.send_error(404, "File not found") | |
| return None | |
| self.send_response(200) | |
| self.send_header("Content-type", ctype) | |
| if path.endswith(".pbf"): | |
| self.send_header("Content-Encoding", "gzip") | |
| fs = os.fstat(f.fileno()) | |
| self.send_header("Content-Length", str(fs.st_size)) | |
| self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) | |
| self.end_headers() | |
| return f | |
| os.chdir(DIRECTORY) | |
| with socketserver.TCPServer(("", PORT), CustomHandler) as httpd: | |
| print("Serving at http://localhost:{}".format(PORT)) | |
| print("Serving directory: {}".format(DIRECTORY)) | |
| httpd.serve_forever() | |
| EOF | |
| # --- プレースホルダの置換 --- | |
| # __PORT__ を設定値に置換 | |
| sed -i.bak "s/__PORT__/$PORT/g" "$PYTHON_SERVER" | |
| # __DIRECTORY__ を絶対パスに置換 | |
| ABS_DIR=$(cd "$DIRECTORY" && pwd) | |
| sed -i.bak "s#__DIRECTORY__#$ABS_DIR#g" "$PYTHON_SERVER" | |
| rm -f "$PYTHON_SERVER.bak" | |
| # ==== サーバーの起動 ==== | |
| python3 "$PYTHON_SERVER" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment