我正在尝试使用 netcat 编写一个小型 HTTP 服务器。对于纯文本文件,这工作正常,但当我尝试发送图片时,浏览器仅显示损坏图像的图标。
我所做的就是提取所请求文件的 mime 类型和大小,并将其发送给客户端。
我的示例图片的请求标头如下所示:
HTTP/1.0 200 OK
Content-Length: 197677
Content-Type: image/jpeg
这是我的 bash 脚本,我使用 netcat 工具的 -e 选项启动它:
#!/bin/bash
# -- OPTIONS
index_page=index.htm
error_page=notfound.htm
# -- CODE
# read request
read -s input
resource=$(echo $input | grep -P -o '(?<=GET \/).*(?=\ )') # extract requested file
[ ! -n "$resource" ] && resource=$index_page # if no file requested, set to default
[ ! -f "$resource" ] && resource=$error_page # if requested file not exists, show error pag
# generate output
http_content_type=$(file -b --mime-type $resource) # extract mime type
case "$(echo $http_content_type | cut -d '/' -f2)" in
html|plain)
output=$(cat $resource)
# fix mime type for plain text documents
echo $resource | grep -q '.css$' && http_content_type=${http_content_type//plain/css}
echo $resource | grep -q '.js$' && http_content_type=${http_content_type//plain/javascript}
;;
x-php)
output=$(php $resource)
http_content_type=${http_content_type//x-php/html} # fix mime type
;;
jpeg)
output=$(cat $resource)
;;
png)
output=$(cat $resource)
;;
*)
echo 'Unknown type'
esac
http_content_length="$(echo $output | wc -c | cut -d ' ' -f1)"
# sending reply
echo "HTTP/1.0 200 OK"
echo "Content-Length: $http_content_length"
echo -e "Content-Type: $http_content_type\n"
echo $output
如果有人能够帮助我,我会很高兴:-)
我希望二进制数据中的特殊字符在您的 shell 脚本中处于活动状态。
我建议您通过以下方式获取文件大小:
http_content_length=`stat -c '%s' $resource`
然后你“发送”它:
...
echo -e "Content-Type: $http_content_type\n"
cat $resource
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)