From e9dc49691a8c74784a8d92580768e001704c1f27 Mon Sep 17 00:00:00 2001 From: Arthur Khachaturov Date: Fri, 26 Jul 2024 13:20:56 +0300 Subject: [PATCH] feat: redirect response --- src/http_server.sh | 2 +- src/request.sh | 3 +-- src/response.sh | 10 ++++++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/http_server.sh b/src/http_server.sh index 2518127..a7a4fc9 100644 --- a/src/http_server.sh +++ b/src/http_server.sh @@ -65,7 +65,7 @@ http::get() { http::route "$1" "GET" "$2"; } http::_static_file() { local uri_path="${request_path#"${HTTP_REQUEST_GLOB%'**'}"}" local filename="${HTTP_STATIC_FOLDER}/${uri_path}" - [[ -z "${uri_path}" || ! -f "${filename}" || "${filename}" == *".."* ]] && http::response 404 && return 1 + [[ -z "${uri_path}" || ! -f "${filename}" || "${filename}" == *".."* ]] && http::response 400 && return 1 http::file "${filename}" } diff --git a/src/request.sh b/src/request.sh index 2a9ac37..4a38ee3 100644 --- a/src/request.sh +++ b/src/request.sh @@ -17,13 +17,12 @@ http::_parse_headers() { http::_parse_body() { cat - >/dev/null; } # TODO http::_route_request() { - [[ -z "${HTTP_SUPPORTED_METHODS[${request_method}]}" ]] && http::response 501 && return 1 + [[ -z "${HTTP_SUPPORTED_METHODS[${request_method}]}" ]] && { http::response 501; return 1; } local glob_endpoint handler path_found for glob_endpoint in "${!http__all_routes[@]}"; do # FIXME O(n) # shellcheck disable=SC2053 if [[ "${request_path}" == ${glob_endpoint} ]]; then - declare -rx HTTP_REQUEST_GLOB="${glob_endpoint}" path_found=1 break fi diff --git a/src/response.sh b/src/response.sh index 12114b0..b7ca79d 100644 --- a/src/response.sh +++ b/src/response.sh @@ -68,6 +68,16 @@ http::file() { } +# calle provides local -A response_headers +# $1 = url, $2 = status code (301/302, optional) +http::redirect() { + local status_code="${2:-302}" + [[ -z "$1" ]] && { http::response 500 && return 1; } + http::_response_base_headers "${status_code}" + response_headers["Location"]="$1" + http::_output_response_headers +} + # calle provides local -A response_headers # $1 = filename http::html() { response_headers["Content-Type"]="text/html" http::file "$@"; }