Minimal web server using netcat

后端 未结 14 775
借酒劲吻你
借酒劲吻你 2020-12-04 05:15

I\'m trying to set up a minimal web server using netcat (nc). When the browser calls up localhost:1500, for instance, it should show the result of a function (date

14条回答
  •  醉梦人生
    2020-12-04 05:40

    I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.

    I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):

    rm -f out
    mkfifo out
    trap "rm -f out" EXIT
    while true
    do
      cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
        export REQUEST=
        while read -r line
        do
          line=$(echo "$line" | tr -d '\r\n')
    
          if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
          then
            REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
          elif [ -z "$line" ] # empty line / end of request
          then
            # call a script here
            # Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
            ./a_script.sh > out
          fi
        done
      )
    done
    

    And my a_script.sh (with your need):

    #!/bin/bash
    
    echo -e "HTTP/1.1 200 OK\r"
    echo "Content-type: text/html"
    echo
    
    date
    

提交回复
热议问题