From 842cd856a49d24212dbc79a1b9914ce382a0b5a1 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Wed, 30 Dec 2015 14:50:58 +0200 Subject: [PATCH] Added transparent compression support to helloworldserver example --- examples/helloworldserver/README.md | 4 +++- examples/helloworldserver/helloworldserver.go | 21 +++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/examples/helloworldserver/README.md b/examples/helloworldserver/README.md index 37bf02283d..80e801ecf4 100644 --- a/examples/helloworldserver/README.md +++ b/examples/helloworldserver/README.md @@ -1,6 +1,8 @@ # HelloWorld server example -Displays various request info. +* Displays various request info. +* Sets response headers and cookies. +* Supports transparent compression. # How to build diff --git a/examples/helloworldserver/helloworldserver.go b/examples/helloworldserver/helloworldserver.go index f4c9c3ec4d..22b518aa4b 100644 --- a/examples/helloworldserver/helloworldserver.go +++ b/examples/helloworldserver/helloworldserver.go @@ -8,12 +8,20 @@ import ( "github.com/valyala/fasthttp" ) -var addr = flag.String("addr", ":8080", "TCP address to listen to") +var ( + addr = flag.String("addr", ":8080", "TCP address to listen to") + compress = flag.Bool("compress", false, "Whether to enable transparent response compression") +) func main() { flag.Parse() - if err := fasthttp.ListenAndServe(*addr, requestHandler); err != nil { + h := requestHandler + if *compress { + h = fasthttp.CompressHandler(h) + } + + if err := fasthttp.ListenAndServe(*addr, h); err != nil { log.Fatalf("Error in ListenAndServe: %s", err) } } @@ -35,4 +43,13 @@ func requestHandler(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request) ctx.SetContentType("text/plain; charset=utf8") + + // Set arbitrary headers + ctx.Response.Header.Set("X-My-Header", "my-header-value") + + // Set cookies + var c fasthttp.Cookie + c.SetKey("cookie-name") + c.SetValue("cookie-value") + ctx.Response.Header.SetCookie(&c) }