Search code examples
imagegogo-iris

Golang Iris Web - Serve 1x1 pixel


I'm new to Golang and trying to use a framework called iris.

My problem is how to serve 1x1 gif pixel, not using c.HTML context, but the way the browser title becomes 1x1 image gif. The image will be used for tracking.

Any help will be deeply appreciated.


Solution

  • Attention: I'm not really familiar with iris so the solution maybe not idiomatic.

    package main
    
    import (
        "github.com/kataras/iris"
        "image"    
        "image/color"
        "image/gif"
    )
    
    func main() {
    
        iris.Get("/", func(ctx *iris.Context) {
            img := image.NewRGBA(image.Rect(0, 0, 1, 1)) //We create a new image of size 1x1 pixels
            img.Set(0, 0, color.RGBA{255, 0, 0, 255}) //set the first and only pixel to some color, in this case red
    
            err := gif.Encode(ctx.Response.BodyWriter(), img, nil) //encode the rgba image to gif, using gif.encode and write it to the response
            if err != nil {
                panic(err) //if we encounter some problems panic
            }
            ctx.SetContentType("image/gif") //set the content type so the browser can identify that our response is actually an gif image
        })
    
        iris.Listen(":8080")
    }
    

    Links for better understanding: