API Response Compression in NodeJS (Express) and Go (Echo)
Published in
2 min readJul 31, 2021
For API response which have big response size we could reduce its size by using compression. Requesting HTTP request with the ‘Accept-Encoding’ Header the server can response in compressed output in supported encoding
Example of NodeJS/Express simulating huge response (~550k bytes)
const express = require(‘express’);const app = express();app.get(‘/’, function(req, res) { res.send(‘hello world’.repeat(50000));});app.listen(3000, function(err) { if (err) console.log(err); console.log(“Server listening on PORT 3000”);});
To compress response in NodeJS/Express we can add compression middleware which will handle ‘Accept-Encoding’
const express = require('express');const app = express();const compression = require('compression');app.use(compression());app.get('/', function(req, res) { res.send('hello world'.repeat(50000));});app.listen(3000, function(err) { if (err) console.log(err); console.log("Server listening on PORT 3000");});
After adding compression middleware we can reduce output bytes to only 1115 bytes! (The size after compressed will vary base on the input pattern)
Example of Go with Echo simulating huge response
package mainimport (
"net/http"
"strings"
"github.com/labstack/echo/v4"
)func main() {
e := echo.New() e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, strings.Repeat("Hello world", 50000))
})
e.Logger.Fatal(e.Start(":8080"))
}
Echo framework also support compression middleware.
package mainimport (
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)func main() { e := echo.New()
e.Use(middleware.Gzip())
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, strings.Repeat("Hello world", 50000))
})
e.Logger.Fatal(e.Start(":8080"))}
References