douliang1891
douliang1891
2016-09-17 07:01
浏览 49
已采纳

Golang Iris Web-服务1x1像素

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douye2020
    douye2020 2016-09-17 08:00
    已采纳

    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:

    点赞 评论

相关推荐