Fiber: 馃 How to compress response myself?

Created on 2 Aug 2020  路  9Comments  路  Source: gofiber/fiber

Question description

I'm doing some forbidden magic, sending the generated CSS to the user, but I can't find a way to do it with compression. So, how can I do that with fiber?

Code snippet

package main

import "github.com/gofiber/fiber"

func main() {
  app := fiber.New()

  app.Get("/css/app.css", NewCSSHandler("./public/css"))
}

func NewCSSHandler(dir string) func(*fiber.Ctx) {
  // Getting content of all css files in dir and minifies it
  var data []byte = doMagic()

  return func(ctx *fiber.Ctx) {
    ctx.Set("Content-Type", "text/css")
    ctx.Set("Content-Length", strconv.Itoa(len(data)))

    ctx.SendBytes(data)
  }
}
馃 Question

All 9 comments

Hi @Terisback, use our compress middleware to enable compression for deflate, gzip and brotli:

app.Get("/css/app.css", middleware.Compress(), NewCSSHandler("./public/css"))

You can find more examples here https://github.com/gofiber/fiber/blob/master/middleware/compress.md

@Fenny I forgot to mention that I already using compression (as middleware), but on site I get css without it

Will check your case in hour

Could you show us the response headers for the css file? Keep in mind that the browser automatically unpacks the compressed response. Maybe you are talking about minification ( https://github.com/tdewolff/minify#css )

You could compare the content length when turning compression on and off to see if it has effect.

PS: In order to compress, the response needs to be bigger than xKb (I forgot what the threshold is)

image
image

br is brotli?
I guess it's compressing?

If it is, compressing is working

so, thanks 馃憣

Yeah, seems to work like it should 馃憤

PS: Fiber sets the content-length header for you 馃槈

Was this page helpful?
0 / 5 - 0 ratings