Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display gif image with webserver in Go (golang)

I'm trying to output a 1x1 transparent GIF image (pre-generated in base64) with this simple Go program, although I can't seem to get it working. Does anyone have idea on how to do this either with the pre-generated base64 string or with a file from disk?

I appreciate the help.


package main

import (
       "net/http"
       "io"
       "encoding/base64"
)

const base64GifPixel = "R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="

func respHandler(res http.ResponseWriter, req *http.Request) {
    res.Header().Set("Content-Type","image/gif")
    output,_ := base64.StdEncoding.DecodeString(base64GifPixel)
    io.WriteString(res,string(output))
}


func main() {
    http.HandleFunc("/", respHandler)
    http.ListenAndServe(":8086", nil)
}
like image 984
hartfordfive Avatar asked Sep 12 '13 13:09

hartfordfive


2 Answers

Seems to be working fine here:

$ wget -q -O file.gif http://localhost:8086
$ file file.gif
file.gif: GIF image data, version 89a, 1 x 1

How are you verifying that it is not working? If you access it with a web browser, I suppose it'll show an empty page with a transparent pixel in it, which is a bit hard to spot. :-)

As a side note, checking errors is strongly recommended, even in sample code (many times the sample code explains itself).

like image 166
Gustavo Niemeyer Avatar answered Nov 03 '22 18:11

Gustavo Niemeyer


works for me too. by the way, if you are doing this as a part of a beacon/tracking pixel, you could simply return a 204 no content (it's 35 bytes smaller than the gif and it can serve the exact same purpose):

func EventTracker(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.NotFound(w, r)
        return
    }
    //insert tracking logic here
    w.WriteHeader(http.StatusNoContent)
}
like image 33
orcaman Avatar answered Nov 03 '22 18:11

orcaman