Ruby, CGI and the attack of the ignorant
I have been developing Rails applications for a year or two now and have even deployed a couple on my own Media Temple account (no linkage, sorry), however I’d never attempted to put together a simple ruby script in my cgi-bin.
In the past, I have written python and perl cgi scripts, but never ruby. So, today I started working a little script to help me quickly setup SVN repositories… But, I quickly found that all my knowledge of UNIX, scripting and CGI equated to squat when I was greeted with a starkly contrasted “Internal Application Error” page - otherwise known as an HTTP 500 error.
Debugging the problem, I checked that:
- My script had 755 permissions
- The script belonged to the correct group
- The shebang line was correct: #!/usr/bin/env ruby
- I ran the script from the command line
- But, everything seemed fine.
Finally, I turned on error logging from the Media Temple (Plesk) control panel and refreshed the page again. On inspecting the error log, I noticed the line “Premature end of script headers” - What the heck is that???
After quite a bit of Googling to find the actual meaning of this error, it hit home that unlike PHP, general-purpose scripting language - such as ruby - don’t send a default set of HTTP headers to the browser and hence Apache wasn’t sure what to do with the results from the CGI.
Adding the following line fixed my troubles and allowed me to start building out my little utility:
print "Content-type: text/html\\n\\n"
For anyone who wants a very quick “base” script to check your servers’ setup and start building your own ruby-cgi script, try throwing this into a *.cgi file in your cgi-bin:
#!/usr/bin/env ruby
print "Content-type: text/html\\n\\n"
print "Hello world"