title: Reading image from HTTP request's body in Go
body: <p>I'm playing with Go (first time ever) and I want to build a tool to retrieve images from Internet and cut them (even resize) but I'm stuck on the first step.</p>
  
  <pre><code>package main
  
  import (
    "fmt"
    "http"
  )
  
  var client = http.Client{}
  
  func cutterHandler(res http.ResponseWriter, req *http.Request) {
    reqImg, err := client.Get("http://www.google.com/intl/en_com/images/srpr/logo3w.png")
    if err != nil {
      fmt.Fprintf(res, "Error %d", err)
      return
    }
    buffer := make([]byte, reqImg.ContentLength)
    reqImg.Body.Read(buffer)
    res.Header().Set("Content-Length", fmt.Sprint(reqImg.ContentLength)) /* value: 7007 */
    res.Header().Set("Content-Type", reqImg.Header.Get("Content-Type")) /* value: image/png */
    res.Write(buffer)
  }
  
  func main() {
    http.HandleFunc("/cut", cutterHandler)
    http.ListenAndServe(":8080", nil) /* TODO Configurable */
  }
  </code></pre>
  
  <p>I'm able to request an image (let's use Google logo) and to get its kind and size.</p>
  
  <p>Indeed, I'm just re-writing the image (look at this as a toy "proxy"), setting Content-Length and Content-Type and writing the byte slice back but I get it wrong somewhere. See how it looks the final image rendered on Chromium 12.0.742.112 (90304):</p>
  
  <p><img src="https://i.stack.imgur.com/4L5f7.png" alt="Grotesque result"></p>
  
  <p>Also I checked the downloaded file and it is a 7007 bytes PNG image. It should be working properly if we look at the request:</p>
  
  <p></p>
  
  <blockquote>
    <p>GET /cut HTTP/1.1<br/>
    User-Agent: curl/7.22.0 (i486-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.0e zlib/1.2.3.4 libidn/1.23 libssh2/1.2.8 librtmp/2.3<br/>
    Host: 127.0.0.1:8080<br/>
    Accept: <em>/</em></p>
    
    <p>HTTP/1.1 200 OK<br/>
    Content-Length: 7007<br/>
    Content-Type: image/png<br/>
    Date: Tue, 27 Dec 2011 19:51:53 GMT</p>
    
    <p>[PNG data]</p>
  </blockquote>
  
  <p>What do you think I'm doing wrong here?</p>
  
  <p>Disclaimer: I'm scratching my own itch, so probably I'm using the wrong tool :) Anyway, I can implement it on Ruby but before I would like to give Go a try.</p>
  
  <p>Update: still scratching itches but... I think this is going to be a good side-of-side project so I'm opening it <a href="https://github.com/imdario/go-lazor" rel="noreferrer">https://github.com/imdario/go-lazor</a> If it is not useful, at least somebody can find usefulness with the references used to develop it. They were for me.</p>