Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get post content with groovy listening on a port?

I wrote the following simple groovy code that handles a request.

if (init)
  data = ""

if (line.size() > 0) {
  data += "--> " + line + "\n"
} else {
  println "HTTP/1.1 200 OK\n"
  println data
  println "----\n"
  return "success"
}

I then run it by doing groovy -l 8888 ServerTest.groovy However, it doesn't seem to print any POST data. I am testing it by doing curl -d "d=test" http://localhost:8888/ Does anybody know how to get that data in groovy?

like image 495
Amir Raminfar Avatar asked Dec 05 '25 19:12

Amir Raminfar


1 Answers

In order for the port listening option to work, you have to also use the -n or -p options.

Example:

// test.groovy
println "Got $line from socket"

$ groovy -n -l8888 test.groovy &
groovy is listening on port 8888
$ echo hello | nc localhost 8888
Got hello from socket
$

EDIT: Also, note that you are getting a single line from a socket, not a complete HTTP request. So in the case of a GET, you're going to get multiple lines to process for each request, looking something like this:

GET / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

The whole request is terminated by a blank line. With a POST, it'll look something like this:

POST / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

d=test

The request is the same, except after the blank line that terminates the GET, is the POST data. Unfortunately, the POST data is not terminated with a newline, and groovy is using line buffered input, so it just sits there waiting for a newline.

However, you can force it to proceed by closing your end of the socket. Try something like this:

System.err.println(line) // log the incoming data to the console

if (line.size() == 0) {
    println "HTTP/1.1 200 OK\r\n\r\nhello"
    socket.shutdownOutput()
}

Then groovy will flush the buffer and finish closing other end, and you'll have your POST data.

like image 92
ataylor Avatar answered Dec 08 '25 20:12

ataylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!