Book Image

Hands-On RESTful Web Services with Go - Second Edition

By : Naren Yellavula
Book Image

Hands-On RESTful Web Services with Go - Second Edition

By: Naren Yellavula

Overview of this book

Building RESTful web services can be tough as there are countless standards and ways to develop API. In modern architectures such as microservices, RESTful APIs are common in communication, making idiomatic and scalable API development crucial. This book covers basic through to advanced API development concepts and supporting tools. You’ll start with an introduction to REST API development before moving on to building the essential blocks for working with Go. You’ll explore routers, middleware, and available open source web development solutions in Go to create robust APIs, and understand the application and database layers to build RESTful web services. You’ll learn various data formats like protocol buffers and JSON, and understand how to serve them over HTTP and gRPC. After covering advanced topics such as asynchronous API design and GraphQL for building scalable web services, you’ll discover how microservices can benefit from REST. You’ll also explore packaging artifacts in the form of containers and understand how to set up an ideal deployment ecosystem for web services. Finally, you’ll cover the provisioning of infrastructure using infrastructure as code (IaC) and secure your REST API. By the end of the book, you’ll have intermediate knowledge of web service development and be able to apply the skills you’ve learned in a practical way.
Table of Contents (16 chapters)

Understanding Go's net/http package

Accepting HTTP requests is the primary goal of a web server. In Go, there is a system-level package that helps developers create HTTP servers and clients. The name of the package is net/http. We can understand the functionality of the net/http package by creating a small example. The example accepts an incoming request and returns the timestamp of the server. Let us see the steps for creating such a server:

  1. Create the program file as follows:
touch -p $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Now, we have a file where we can develop a server with a Health Check API that returns a date/time string.

  1. Import the net/http package and create a function handler called HealthCheck. The http.HandleFunc is a method that takes a route and a function handler as its arguments. This function handler has to return an http.ResponseWriter object:
package main

import (
"io"
"log"
"net/http"
"time"
)

// HealthCheck API returns date time to client
func HealthCheck(w http.ResponseWriter, req *http.Request) {
currentTime := time.Now()
io.WriteString(w, currentTime.String())
}

func main() {
http.HandleFunc("/health", HealthCheck)
log.Fatal(http.ListenAndServe(":8000", nil))
}

The preceding code creates a HealthCheck function and attaches it to an HTTP route. HandleFunc is used to attach a route pattern to a handler function. ListenAndServe starts a new HTTP server. It returns an error if the server launch is unsuccessful. It takes address:port as the first argument and the second argument is nil, which says use the default multiplexer. We will see multiplexers in detail in the upcoming sections.

Use the log function to debug potential errors. The ListenAndServe function returns an error if there is one.
  1. Now, we can start the web server using this command:
go run $GOPATH/src/github.com/git-user/chapter2/healthCheck/main.go

Run the healthCheck.go file from a shell.

  1. Now, fire up a shell or browser to see the server in action. Here, we use the curl request:
curl -X GET http://localhost:8000/health

The response is as follows:

2019-04-10 17:54:05.450783 +0200 CEST m=+6.612810181

Go has a different concept for handling request and response. We used the io library to write to the response. For web development, we can use a template to automatically fill in the details. Go's internal URL handlers use a ServeMux multiplexer. In the next section, we will discuss more on ServeMux, a built-in URL router in Go.