4
netcat을 사용하여 작은 HTTP 서버를 작성하려고합니다. 일반 텍스트 파일의 경우에는 정상적으로 작동하지만 사진을 보내려고하면 브라우저가 깨진 이미지의 아이콘 만 표시합니다. 내가하는 일은 요청한 파일의 mime-type과 크기를 추출하여 클라이언트에게 전달하는 것입니다. 내 예를 들어 사진의 요청의 헤더는 다음과 같습니다netcat을 사용하여 이미지를 포함한 HTTP 응답 제공
HTTP/1.0 200 OK
Content-Length: 197677
Content-Type: image/jpeg
이 내가 netcat을 도구의 -e 옵션을 사용하여 실행 내 bash는 스크립트입니다
#!/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
이 경우 매우 기뻐할 것입니다 누군가 나를 도울 수 있습니다 :-)
이 작품은, 대단히 감사합니다. PHP 코드를 구문 분석하기 위해 출력 변수와 함께이 해결 방법을 사용했지만이 방법을 찾을 수 없습니다. – flappix
@flappix : 임시 파일을 만들고 PHP 출력을 작성하고 $ resource를 임시 파일 이름으로 설정 하시겠습니까? – MattH
내가 이런 식으로 해결했지만 도움이되는 의견을 보내 주셔서 감사합니다 http://ompldr.org/vaHdnYg/httpservera 편집 : 좋아요, 당신의 아이디어가 더 좋고, 제가 그것을 바꿨습니다 ;-) thx – flappix