昨天,今天,明天,每天的每天,你是否都多懂得一点点...

星期四, 八月 23, 2018

[网络技术] Create a HTTP Request Body Log Server within a minute with Docker

Tags: Telegram, Telegram Bot, HTTP Body Log, PHP, Docker

I am playing with telegram bot these two days. I used a google script web app as the web server to handle telegram's request. I would like to see the requests sent by telegram bot. So I forward the content from telegram to my own server.

[javascript]
function doPost(e){
  var body = JSON.parse(e.postData.contents);
  var payload = preparePayload(body);
  var data = {
    "method": "post",
    "payload": payload
  }
  UrlFetchApp.fetch("https://api.telegram.org/botMyBotKEY/", data);
  
  var dataFromTelegram = {
    "method": "post",
    "payload": e.postData.contents
  }
  UrlFetchApp.fetch("http://test.dengnz.com", dataFromTelegram);

}
[/javascript]


So I need my server to log the request body into a log file. The two tools comes into my mind are nginx and php. 

I tried nginx, but to let nginx log HTTP request body, I will either need echo_read_request_body module or fast CGI module. Unfortunately, you cannot add these modules into official nginx docker container.  And you have to use newer version of nginx so that you can do json_escape to make sure you don't see a lot of \x22 in your json log.

I also tried a third party nginx image (nmarus/nginx-full), it worked with some minor config, but it's an old version of nginx which cannot do json escape. 

So I end up with using a docker php server, which is so much easier to setup. It will just take you a minute.

First, create a file call index.php with the following content

[php]
<?php $req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, '['.date("c").']'.$req_dump."\n");
fclose($fp);
?>
[/php]

Then run the following command within of folder of above file

[bash]
docker run -it --rm -d -p 80:80 --name phpHTTPLog \
   -v "$PWD":/usr/src/myapp -w /usr/src/myapp php:7.0-cli php -S 0.0.0.0:80
[/bash]


If you are behind a nginx-proxy, you may run something like this with your own config
 
[bash]
docker run -it --rm -d -p 8080:80 --name phpHTTPLog \
    --network wp-net \
    --network-alias httpLog \
    -e VIRTUAL_HOST=test.dengnz.com,httpLog.dengnz.com \
    -e "LETSENCRYPT_HOST=test.dengnz.com,httpLog.dengnz.com" \
    -e "LETSENCRYPT_EMAIL=soody@qq.com" \
   -v "$PWD":/usr/src/myapp -w /usr/src/myapp php:7.0-cli php -S 0.0.0.0:80
[/bash]

Now run this command to watch the log file

[bash]
tail -f request.log
[/bash]

Now you can see all the requests send by telegram bot (or whatever you are testing)



#img1#


#imge2#



When you are done, Ctrl+C to exit tail command then run

[bash]
docker stop phpHTTPLog
[/bash]

to stop and delete the docker container


Note that you may need to add sudo before docker command if you are not running under root user.

没有评论:

其它博客地址

此博客的同步博客地址: http://fengnz.wordpress.com
这里进入我的MSN SPACE.