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)

Implementing HTTP request routing using Gorilla Mux

Go’s net/http package offers a lot of functionalities for URL routing of the HTTP requests. One thing it doesn’t do very well is dynamic URL routing. Fortunately, we can achieve this with the gorilla/mux package, which we will be covering in this recipe.

How to do it...

In this recipe, we will use gorilla/mux to define a few routes, like we did in our previous recipe, along with their handlers or resources. As we have already seen in one of our previous recipes, to use external packages, first we have to install the package using the go get command or we have to copy it manually to $GOPATH/src or $GOPATH. We will do the same in the recipe as well. Perform the following steps:

  1. Install github.com/gorilla/mux using the go get command, as follows:
$ go get github.com/gorilla/mux
  1. Create http-server-gorilla-mux-routing.go and copy the following content:
package main
import
(
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var GetRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("Hello World!"))
}
)
var PostRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("It's a Post Request!"))
}
)
var PathVariableHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("Hi " + name))
}
)
func main()
{
router := mux.NewRouter()
router.Handle("/", GetRequestHandler).Methods("GET")
router.Handle("/post", PostRequestHandler).Methods("POST")
router.Handle("/hello/{name}",
PathVariableHandler).Methods("GET", "PUT")
http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
}
  1. Run the program with the following command:
$ go run http-server-gorilla-mux-routing.go

How it works...

Once we run the program, the HTTP server will start locally listening on port 8080, and accessing http://localhost:8080/, http://localhost:8080/post, and http://localhost:8080/hello/foo from a browser or command line will produce the message defined in the corresponding handler definition. For example, execute http://localhost:8080/ from the command line, as follows:

$ curl -X GET -i http://localhost:8080/

This will give us the following response from the server:

We could also execute http://localhost:8080/hello/foo from the command line, as follows:

$ curl -X GET -i http://localhost:8080/hello/foo

This will give us the following response from the server:

Let's understand the code changes we made in this recipe:

  1. First, we defined GetRequestHandler and PostRequestHandler, which simply write a message on an HTTP response stream, as follows:
var GetRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("Hello World!"))
}
)
var PostRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("It's a Post Request!"))
}
)
  1. Next, we defined PathVariableHandler, which extracts request path variables, gets the value, and writes it to an HTTP response stream, as follows:
var PathVariableHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("Hi " + name))
}
)
  1. Then, we registered all these handlers with the gorilla/mux router and instantiated it, calling the NewRouter() handler of the mux router, as follows:
func main() 
{
router := mux.NewRouter()
router.Handle("/", GetRequestHandler).Methods("GET")
router.Handle("/post", PostCallHandler).Methods("POST")
router.Handle("/hello/{name}", PathVariableHandler).
Methods("GET", "PUT")
http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
}