Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect usage of os.NewFile in Go
    primarykey
    data
    text
    <p>I'm attempting to compose an image in memory and send it out through http.ResponseWriter without ever touching the file system.</p> <p>I use the following to create a new file:</p> <pre><code>file := os.NewFile(0, "temp_destination.png") </code></pre> <p>However, I don't seem to be able to do anything at all with this file. Here is the function I'm using (which is being called within an http.HandleFunc, which just sends the file's bytes to the browser), which is intended to draw a blue rectangle on a temporary file and encode it as a PNG:</p> <pre><code>func ComposeImage() ([]byte) { img := image.NewRGBA(image.Rect(0, 0, 640, 480)) blue := color.RGBA{0, 0, 255, 255} draw.Draw(img, img.Bounds(), &amp;image.Uniform{blue}, image.ZP, draw.Src) // in memory destination file, instead of going to the file sys file := os.NewFile(0, "temp_destination.png") // write the image to the destination io.Writer png.Encode(file, img) bytes, err := ioutil.ReadAll(file) if err != nil { log.Fatal("Couldn't read temporary file as bytes.") } return bytes } </code></pre> <p>If I remove the <code>png.Encode</code> call, and just return the file bytes, the server just hangs and does nothing forever.</p> <p>Leaving the <code>png.Encode</code> call in results in the file bytes (encoded, includes some of the PNG chunks I'd expect to see) being vomited out to stderr/stdout (I can't tell which) and server hanging indefinitely.</p> <p>I assume I'm just not using os.NewFile correctly. Can anyone point me in the right direction? Alternative suggestions on how to properly perform in-memory file manipulations are welcome.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload