Book Image

Go Web Development Cookbook

By : Arpit Aggarwal
Book Image

Go Web Development Cookbook

By: Arpit Aggarwal

Overview of this book

Go is an open source programming language that is designed to scale and support concurrency at the language level. This gives you the liberty to write large concurrent web applications with ease. From creating web application to deploying them on Amazon Cloud Services, this book will be your one-stop guide to learn web development in Go. The Go Web Development Cookbook teaches you how to create REST services, write microservices, and deploy Go Docker containers. Whether you are new to programming or a professional developer, this book will help get you up to speed with web development in Go. We will focus on writing modular code in Go; in-depth informative examples build the base, one step at a time. You will learn how to create a server, work with static files, SQL, NoSQL databases, and Beego. You will also learn how to create and secure REST services, and create and deploy Go web application and Go Docker containers on Amazon Cloud Services. By the end of the book, you will be able to apply the skills you've gained in Go to create and explore web applications in any domain.
Table of Contents (13 chapters)

Optimizing HTTP server responses with GZIP compression

GZIP compression means sending the response to the client from the server in a .gzip format rather than sending a plain response and it’s always a good practice to send compressed responses if a client/browser supports it.

By sending a compressed response we save network bandwidth and download time eventually rendering the page faster. What happens in GZIP compression is the browser sends a request header telling the server it accepts compressed content (.gzip and .deflate) and if the server has the capability to send the response in compressed form then sends it. If the server supports compression then it sets Content-Encoding: gzip as a response header, otherwise it sends a plain response back to the client, which clearly means asking for a compressed response is only a request by the browser and not a demand. We will be using Gorilla’s handlers package to implement it in this recipe.

How to do it...

In this recipe, we are going to create an HTTP server with a single handler, which will write Hello World! on an HTTP response stream and use a Gorilla CompressHandler to send all the responses back to the client in the .gzip format. Perform the following steps:

  1. To use Gorilla handlers, first we need to install the package using the go get command or copy it manually to $GOPATH/src or $GOPATH, as follows:
$ go get github.com/gorilla/handlers
  1. Create http-server-mux.go and copy the following content:
package main
import
(
"io"
"net/http"
"github.com/gorilla/handlers"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
func helloWorld(w http.ResponseWriter, r *http.Request)
{
io.WriteString(w, "Hello World!")
}
func main()
{
mux := http.NewServeMux()
mux.HandleFunc("/", helloWorld)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT,
handlers.CompressHandler(mux))
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Run the program with the following command:
$ go run http-server-mux.go

How it works...

Once we run the program, the HTTP server will start locally listening on port 8080.

Opening http://localhost:8080 in a browser will display Hello World! from the server with the Content-Encoding response header value gzip, as shown in the following screenshot:

Hello World!

Let’s understand what each line in the program means:

  • package main: This defines the package name of the program.
  • import ( "io" "net/http" "github.com/gorilla/handlers" ): This is a preprocessor command that tells the Go compiler to include all files from io, net/http, and the github.com/gorilla/handlers package.
  • const ( CONN_HOST = "localhost" CONN_PORT = "8080" ): We declare constants in a Go program using the const keyword. Here, we declared two constants—one is CONN_HOST with a value of localhost and another is CONN_PORT with a value of 8080.
  • func helloWorld(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello World!")}: This is a Go function that takes ResponseWriter and Request as input parameters and writes Hello World! on the HTTP response stream.

Next, we declared the main() method from where the program execution begins. As this method does a lot of things, let’s understand it line by line:

  • mux := http.NewServeMux(): This allocates and returns a new HTTP request multiplexer (ServeMux), which matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. One of the benefits of using it is that the program has complete control over the handlers used with the server, although any handlers registered with the DefaultServeMux are ignored.
  • http.HandleFunc("/", helloWorld): Here, we are registering the helloWorld function with the / URL pattern using HandleFunc of the net/http package, which means helloWorld gets executed, passing (http.ResponseWriter, *http.Request) as a parameter to it whenever we access the HTTP URL with the / pattern.
  • err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, handlers.CompressHandler(mux)): Here, we are calling http.ListenAndServe to serve HTTP requests that handle each incoming connection in a separate Goroutine for us. ListenAndServe accepts two parameters—server address and handler. Here, we are passing the server address as localhost:8080 and handler as CompressHandler, which wraps our server with a .gzip handler to compress all responses in a .gzip format.
  • if err != nil { log.Fatal("error starting http server: ", err) return}: Here, we check whether there is any problem in starting the server. If there is, then log the error and exit with a status code of 1.