Reputation: 1275
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)
}
Upvotes: 8
Views: 3208
Reputation: 6561
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)
}
Upvotes: 1
Reputation: 22991
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).
Upvotes: 8