简体   繁体   中英

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM