LoginSignup
4
0

More than 5 years have passed since last update.

Advent of Code 2018 Day1 で OpenResty に入門した

Last updated at Posted at 2018-12-08

Advent of Code 2018 Day1 で OpenResty に入門した

Advent of Code [https://adventofcode.com/] というものを教えてもらったので, 良い機会なので Lua で書いて OpenResty に入門した.
問題の解説とかは特にしない.
公式ドキュメントの「Getting Started」のプラスアルファくらいの内容.

ロジックが書ける Nginx くらいの認識だったが, 色々調べてみて夢広がった.
この感動をみなさんに伝えたかった.

環境

本編

ディレクトリ構成

├── input.txt
├── logs
├── conf
│   └── nginx.conf
└── lua
    └── part1.lua
  • input.txt
    • Advent of Code の input データ
    • OpenResty とは関係ない
  • logs
    • nginx のログ出力先ディレクトリ
    • error.log とか access.log とか
  • conf/nginx.conf, lua/part1.lua
    • 下記で説明

conf/nginx.conf

nginx の設定ファイル.


worker_processes  1;
error_log logs/error.log;

events {
  worker_connections 1024;
}

server {
  listen 8080;
  location / {
    default_type text/html;
    # lua ファイルパス指定
    # nginx の起動オプション(p)にカレントディレクトを指定するため,
    # カレントディレクトリからの相対パス
    content_by_lua_file lua/part1.lua;
  }
}

lua/part1.lua


ngx.req.read_body()
local d = ngx.req.get_body_data()

local result = 0
for v in string.gmatch(d, "(.-)\n") do
    result = result + tonumber(v)
end

ngx.say(result)

実行

nginx 起動

$ openresty -p `pwd`/ -c conf/nginx.conf

リクエスト

$ curl -X POST --data-binary @input.txt http://localhost:8080/
445

感想

4
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
4
0