Fork me on GitHub

26 Aug 2011

Grails Gotcha: Beware HEAD requests when rendering binary output in controllers

Although most Grails controllers render HTML, JSON or XML output it is possible to use them to render binary data as well. We use a controller to render images uploaded by editors into our content management interface. The theory is simple enough, instead of using the render dynamic method or returning a model the controller action just writes bytes directly to the HTTP response stream. Our action looked something like this:

def show = {
    def image = Image.read(params.id)
    if (image) {
        response.contentType = image.contentType
        response.outputStream.withStream { stream ->
            stream << image.bytes
        }
    } else {
        response.sendError SC_NOT_FOUND
    }
}

This seemed to work well enough. However when writing a test I noticed an odd thing. I was using RESTClient to scrape resource URLs out of and make a HEAD request against them to ensure the URLs were valid. Javascript and CSS files were working fine but all the non-static images in the page were getting 404s. Initially I suspected a data setup problem and spent some time ensuring my test was setting data up properly. It was only once I put some debug logging in the controller action that I saw that the controller was actually loading images. The 404 was not coming from the else block in the action as I initially assumed. I tried changing the RESTClient call from head to get and suddenly the image URLs started working!

Once I did that I realised what the problem was. An HTTP HEAD request does not expect a response, in fact a server receiving a HEAD request must not return a response. The response stream that our controller action is writing to is, when the request method is HEAD, actually a no-op stream. When the action completes Grails checks to see if anything has been committed to the response stream and since it has not assumes that we want to render a view by convention. You can probably see where this is going now. The convention is that the request gets forwarded to grails-app/views/<controller>/<action>.gsp which of course does not exist. The forwarded request sets a response code of 404 because there is no GSP!

We caught this bug in our app completely by accident but it could actually have been quite serious. Caching proxies and CDNs may well use a HEAD request to revalidate content and on getting a 404 assume that the URL is no longer valid. If the 404 response itself then gets cached we could get broken images on our site because the CDN tells the client browser there's nothing there.

The solution is simple enough. I changed the controller action to simply set a 200 response code when it gets a HEAD request for a valid image:

def show = {
    def image = Image.read(params.id)
    if (image) {
        if (request.method == "HEAD") {
            render SC_OK
        } else {
            response.contentType = image.contentType
            response.outputStream.withStream { stream ->
                stream << image.bytes
            }
        }
    } else {
        response.sendError SC_NOT_FOUND
    }
}

A neater solution might be to use Grails’ support for mapping actions to request methods so that GET and HEAD requests dispatch to different actions.

63 comments:

James said...

Although strictly speaking the head request should return the number of bytes in the Content-Length header that would be returned in the get request's stream?

Marc Palmer said...

Maybe we need a withRequestMethod block. Could be nice.

Anonymous said...

Her voice,her bright body.Her infinite hike81ai eyes.I no longer love her,
that's certain,but maybe I love her.
Cheap New Era Hats
New Era Fitted Hats
Wholesale Cheap Hats
Cheap Hats
Cheap NCAA Hats

Anonymous said...

Great Code :) Thanks for Sharing



Wedding Websites

Bella Tran said...

Thanks for sharing this quality information with us and i like this.
juegos kizi | happy wheels | juegos kizi | agario | agar io | my little pony games | fireboy and watergirl

Unknown said...

Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.
run 2 game | slitherio | run 2 unblocked | slither io | run 2 game | slither.io

Unknown said...

The article clearly and plainly as I will learn and focus on it baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash

baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash, baixar sonic dash, baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash , baixar sonic dash

Unknown said...

Very helpful advice in this particular post! It’s the little changes that make the largest changes. Thanks for sharing!
strike force kitty 2 | swords and souls 2 | red ball 3 | ninjago games

Unknown said...

شركة عزل اسطح بالدمام
شركة عزل اسطح بالخبر
شركة مكافحة حشرات بالدمام
شركة مكافحة حشرات بالخبر
شركة كشف تسربات المياة بالدمام
شركة كشف تسربات المياة بالخبر
شركة تنظيف مجالس بالدمام
شركة تنظيف مجالس بالخبر
شركة تنظيف سجاد بالدمام
شركة تنظيف سجاد بالخبر
شركة تنظيف بالدمام
شركة تنظيف بالخبر
شركة تسليك مجاري بالدمام
شركة تسليك مجاري بالخبر









Hari Jack said...

Thanks for the informations you shared!! I hope you will continue to have similar posts to share with everyone!
slither io

Unknown said...

iWantv! 'ABS-CBN live spilling' appears with only 1 click! – LopezLink. Jan 28, 2010 - iWantv! gives you a chance to get well known shows in video-on-request and live channel groups. The video-on-request choice makes live gushing of iWant television 2.3.2 for Android – Download Dialect. Creator: ABS-CBN. Security level: 100% safe. Estimate: 3.04MB. Downloads: 12,463. Date: 07.29.16. Bundle Name: com.abscbn.iwantv. IWanTV | LoadCentral Philippines Its administrations incorporate Article source and voice, and portable web alongside the restrictive access to ABS-CBN substance through the IWanTV! application. It was propelled on Article source
ABS-CBN Shows, iWanTV, different substance to be accessible to Shrewd. Sep 27, 2016 - To begin with iWant television, PLDT Home and Savvy endorsers can enlist for a record by means of www.iwantv.com.ph or download the iWant television. iWantv!: Online Free television at your own opportunity | penworks | photoblog Nov 8, 2010 - iWantv is an administration allowed to all SKYBROADBAND and BayanDSL endorsers. Facilitating all the top of the line shows of ABS-CBN, ANC, Studio 23. Get Premium Access on iWantTV with Article source 50! | Starmometer. Nov 13, 2016 - Missing a scene of your most loved primetime teleserye in light of terrible movement is presently a thing previously. With ABS-CBN's iWanTV, I can.
Interpret this page. Liza Soberano and Enrique Gil repeat their very much cherished parts as Agnes and Xander as they top bill "Everlastingly and the sky is the limit from there," the main select substance offering on. the most effective method to download recordings from iwantv » YugaTech | Philippines Tech. BayanDSL and Article source is currently offering live gushing television and video-on-request to all it's DSL endorsers and Sky Broadband clients. Accessible channels incorporate. iWanTV Files – LIONHEARTV. More on the web and cell phone clients keep on watching ABS-CBN programs online by means of the video-on-request and livestreaming administration iWanTV. Article source

ركن كلين said...


شركة مكافحة حشرات بالرياض
شركة مكافحة الناموس بالرياض
شركة مكافحة النمل الاسود بالرياض
شركة مكافحة بق الفراش بالرياض
شركة مكافحة البرص بالرياض
شركة رش مبيدات شمال الرياض
شركة رش مبيدات جنوب الرياض
شركة رش مبيدات شرق الرياض
شركة رش مبيدات غرب الرياض

Media3K said...

The Pinoy TV shows and programs that are aired on Pinoy TV make you proud to be a part of Philippines culture. People also love to watch all Pinoy teleserye of pinoy lambingan because in these shows they get to know about the attest trends in the society and also the current happenings.
Pinoy channel

However said...

T10 League Live Streaming

Unknown said...

PSL live streaming, PSL 2019 live streaming, PSL live streaming. Watch all matches of Pakistan Super League live here. PSL 2019 is starting on 14th February and PSL 4 final match will be played on 17th March at Karachi. Full schedule will be released later.

Unknown said...

Television is already considered as one great part of entertainment for many individuals especially for Filipinos. In every Filipino household, watching television is one among the best sources of entertainment and fun. Almost all Filipinos are into being addicted with watching different shows in television. All over the Philippines, one among the most widely chosen network to watch Pinoy TV Shows is GMA 7. It provides numbers of unique and meaningful TV shows that make every pinoy be addicted on watching television and so proud being a Filipino as well. Most Filipinos are really fanatic of TV show thats why it could be frustrating on their part if they couldnt watch their favorite shows. But due to some reasons like busy schedules some Filipinos dont have time to watch their favorite television shows.

Gaming Lover said...

GOOD
Merry Christmas & Happy New Year
Happy New Year Quotes 2019
Merry Christmas & Happy New Year 2019
Happy New Year Messages Poetry 2019
Happy New Year Resolution 2019
Happy New Year Resolutions 2019
Happy New Year Gift Ideas 2019
Happy New Year Wallpapers 2019

Check Also Today Live Match
Today Live Match Streaming
Today Live Match Prediction
World Cup Live Streaming

Unknown said...

Amazing site..Thanks for sharing..keep update php training in chennai | php training in velachery chennai | php course fees in chennai | best php training institute in chennai

nandhu said...



shareit apk download
shareit downloads
download shareit
download shareit apk
This makes SHAREit an all-in-one app that will come in handy at all times. In addition, the GIFs, wallpapers and stickers that can be found with SHAREit can be personalized, downloaded and shared with friends.

Unknown said...

IPL 2019 Today Match Prediction

CWC 2019 Today Match Prediction

ananthinfo said...

nice post..
mysql dba training institute
mysql dba training in chennai
java training in chennai
best java training institute in chennai
seo training in chennai
seo training institute in chennai
erp training institute in chennai
erp training in chennai

على جمال said...


خدمات ركن كلين لمكافحة الحشرات بالرياض لذلك تحرص شركتنا كأفضل و ارخص شركة مكافحة حشرات بالرياض الشركات الموجودة فى الرياض على التخلص من جميع الأفات الشرسه مثلا الفئران وغيرها من القوارض التى من الممكن ان تكون سبب فى تدمير اغراض اى منزل او قد تسبب بعض الامراض اونقلها.شركة مكافحة النمل الاسود بالرياض-شركة مكافحة الصراصير بالرياض-شركة مكافحة البق بالرياض-شركة مكافحة الوزغ بالرياض-شركة مكافحة الثعابين بالرياض

Cricfrog Prediction said...

Cricket Betting Tips ICC Cricket world cup 2019 Today match prediction who will win tital International Cricket Betting Tips, 100% Fixed Session & Toss report. Astrology today match prediction

ccl6t said...

Get the Today Match Prediction of the World Cup 2019,Momentum Cup, IPL, BPL, BBL, PSL, CSA, and many more. Fantasy Cricket Prediction
Halaplay Prediction, Cricfrogprediction, Dream11 Prediction, Who will Win, etc. here.

Gary said...

Thanks for the wonderful post, check here for the following details

ICC Cricket World cup 2019 Live Streaming

Crichd Live Streaming

Copa America 2019 Fixtures PDF

david williams said...
This comment has been removed by the author.
cmtech said...

Thank you very much for the article information. I will share it with my friends.
cửa cuốn giá bao nhiêu

23 July 2019 said...


our health and often lead to weight gain. Essential fatty acids also help our brain's neurotransmitters to function properly in order to deal with stress, emotions, and cravings that can lead to ove Ultra Fast Keto Boost

APK Guru said...

Nice blog. i really appreciate your efforts.
CricHD Live Streaming

Moonlight Bedding said...

Great article and very informative.
Checkout these amazing Home Decors Modern Rugs for modern living.

BGdoor said...

tậu cửa chính đẹp 2 cánh giống như một giải pháp cho nói chung nội thất trở nên hoàn hảo hơn, đẹp hơn, sang trọng và phá cách thức hơn. cửa chính 2 cánh lệch có diện tích lớn do đó nó vô cùng thích hợp với những căn biệt phủ hay những căn nhà ống cao cấp. Hơn nữa, báo giá cửa gỗ an cường với một bộ cửa chính bằng gỗ 2 cánh đẹp và cao cấp thì gia chủ sẽ không hề lo lắng về việc bị tróc sơn ngay cả khi cánh cửa chính bằng gỗ là món đồ nội thất dễ bị hỏng hóc nhất vì thường xuyên phải chịu các tác động trực tiếp từ thời tiết.

akshayavengala said...

kingroot for pc
kingroot pc
download kingroot pc
kingroot apk
kingoroot
kingroot download
you're working from your PC, download the APK and email it to yourself as an attachment.

ghani khan said...

Nice Article keep it up Can we get Best Graphic Card under 500$

ghani khan said...

Nice Article keep it up Can we get Best 120hz Monitor

homa hakeem said...

شركة تنظيف قصور بجازان
شركة تنظيف بيوت شعر بجازان
شركة تنظيف باابوعريش
شركة تنظيف ببيشه
شركة تنظيف مكيفات بجازان
شركة تنظيف سجاد بجازان
شركة تنظيف كنب بجازان

شركة تنظيف مجالس بجازان
شركة تنظيف منازل بجازان

M.Yakoob said...

thanks for the post really like your efforts
cricbuzz live

Harry said...


Thanks for sharing the requirements. But, I want to ask something different.
I was thinking that how apps like android marketplace are made. Like the ones that offer free apps that are paid
on the Playstore. For example you can consider blackmart alpha, lucky patcher. These days there is a new similar app
in the market and that is AC Market. I read about it on this blog. https://acmarket.website

Let me know if you guys find out something.

ac market Apk 2020

acmarket for ios 2020

acmarket for pc 2020

Download Ac Market 2020

minecraft apk download 2020

Amazon app store apk 2020

App Even apk

app even ios

HOW TO GEEK said...

Are searching for Today match prediction?

Cricstone.com is the best and 100% sure.

المتوكل على الله said...



شركة تنظيف مكيفات بالرياض
افضل شركة تنظيف مكيفات بالرياض
شركة تنظيف مكيفات السبلت بالرياض
تنظيف مكيفات بالرياض
شركة غسيل مكيفات بالرياض

sammer mark said...

WOW! Nice written by author If you tried everything and you are unable to take out your HP printer form error state then contact experts. A team of certified experts will help you to fix your HP Wireless Printer Setup problem. After having the guidance of experts, you will be able to take out printouts by your HP printer.

sammer mark said...

Great post. I like to read your post. I am waiting for your next post. HP Printer setup

sammer mark said...

Great post. I like to read your post. I am waiting for your next post. HP Printer setup

sammer mark said...

Hey! Thanks For Sharing such an informative Post Please Keep it up, I am waiting for your next post.
Can I Setup for HP Printer with Modern Technique
Gude Line for HP Fax Error 388

sammer mark said...

Wow! It is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
Fix CD/DVD Drive Device Driver is Missing in My Laptop
Scan from your HP Photosmart Printer to your mac

williamsonmaccini said...


www.rocketmail.com
this is one the best app for android.

Brooklyn Smith said...

Hey admin! This is my first time here and, Your each and every article provided us valuable and so beneficial subjects information to work on. You have done a wonderful job and, I so much no doubt will make ceгtain to d᧐ not disregard thiѕ website blog and give it a look on a constant baѕіs. Thank you sharing. assignments help australia -
assignment help in melbourne -
Assignment Help Adelaide

Religion World said...

https://www.religionworld.in/support-pure-religion-contribute-to-religion-world/
www.religioworld.in
Religion World wants to make religion a service to the public,
not to the directionless business of beliefs and faiths ( Support Religion ).
We believe those who make any effort honestly, determine its direction.
Your support can make pure religious info balanced and objective.
religionworld
#Supportreligion
#religion
#hindu
#islam
#sikhism
#christanity
#budhism

عبد الله محمد عبدالله said...


شركة تنظيف مكيفات بالرياض
شركة تنظيف شقق بالرياض

عبدالله هادى said...



مكافحة حشرات بالرياض
شركة مكافحة الصراصير بالرياض
شركة مكافحة الفئران بالرياض
شركة مكافحة النمل الابيض بالرياض
شركة رش مبيدات بالرياض
شركة رش دفان بالرياض

Awad Elsyed said...

فني تركيب ستائر بالرياض

فني تركيب اثاث ايكيا بالرياض

تركيب ارضيات باركيه بالرياض

مكافحة حشرات بالرياض

تركيب طارد حمام بالرياض

رش مبيدات بالرياض

نقل عفش بالرياض

نقل اثاث بالرياض

عزل اسطح بالرياض

عزل خزانات بالرياض

كشف تسربات بالرياض


mikejasonuk said...

Eliminate any tapes or materials for bundling consequently. Open the section plate and open the tapes on paper width and longitudinal markers. 123.com.setup Stretch out the piece of paper to the most extreme limit. Take the new plain white paper pack and burden it into the info tray. Drag the markers with the goal that the sheets are tight, however not very close. Whenever you're done, close the paper tray. To try not to print wrong records, adjust ink cartridges. Setup on the scanner is finished. Take the defensive plate on the glass of the scanner. Clean the glass and keep up with the forward looking setup plate. Ensure that the archive is set on the essences of the scanner glass as indicated by the setup markings. Pick OK and delay until the printer is in setup.

Brooklyn Smith said...

After reading your website blogs and web pages I was amazed and so happy after all, My all need fulfil after read your posts. I know that you explain it very well and I hope that other readers will also experience how I feel after reading your articles. Thank you so much admin for this superb post.
Assignment Help Australia - Assignment Help in Adelaide - Best Assignment Help in Brisbane - Australia Assignment Help

Unknown said...

https://www.empowher.com/users/sunilsharma
https://www.sbnation.com/users/sunilsharma1
https://community.teltonika-networks.com/user/sunilsharma
https://www.vivaelbirdos.com/users/sunilsharma1
http://tomiszon.gbzl.pl/profile.php?mode=viewprofile&u=14256
https://forums.dangerousrays.com/memberlist.php?mode=viewprofile&u=16010
https://www.cyclingforums.com/members/sunilsharma.305617/
https://www.hulkshare.com/igpinstitute
https://www.buzzbuzzhome.com/us/person/sunilsharma
https://pixarplanet.com/forums/viewtopic.php?f=1&t=464222

Brooklyn Smith said...

So amazing + useful and what a unique way to shared with others, You writing style is so impressive and unique way to guide others early as possible. Keep up the good work like this. Trust me guys, What a nice and lovely way to inform people and guide them. I like them very much. Thank you for this so beneficial sharing, Good luck buddy. Online statistics homework help - Online college homework help - Online assignment writing service - Online physics homework help

casinositeking 카지노사이트 said...

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn't stop reading. I am impressed with your work and skill. Thank you so much. 바카라

Vmagosu said...



Everyone an extremely breathtaking chance to read from this blog.
It is always so lovely and jam-packed with a great time. 사설경마

경마사이트 said...


This is because the best CBD producers are working with the FDA to ensure its safety. This means that if you research your supplier well, and buy on quality much more than just the price, you will get nothing but the safest, most pure CBD supplements available
경마사이트

magosucowep

sheasen said...

h3f38b5i12 k5o26l6t01 r9c42b1m04 a7y07x7k40 h2o58x9l07 y1s37p4f58

renikash said...

a3h61x7a54 z4o17z2n43 p8p05o0k93 y6i50l4j02 f1y78a7q36 h3z97s2u32

EIbass said...

you have such an interesting and relevant content here, I commend your work out towards this site, thanks for sharing imsubeb past question in pdf format

Samuel Houston said...

On this platform, you will be updated regarding the complete PSL Schedule with a match-to-match, date-by-date, and day-by-day. Also, in the schedule, the venue for all matches will be given the link.

Essien said...

Thank you so much, I appreciate your ability in giving out this knowledge and its a kind motivates content. Thanks so much for sharing. fce potiskum certificate in computer admission form portal

kellywade said...

you can check Nagad Cash Out Charges