Building RESTful Web services with Go
eBook - ePub

Building RESTful Web services with Go

Naren Yellavula, Anshul Joshi

Share book
  1. 316 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Building RESTful Web services with Go

Naren Yellavula, Anshul Joshi

Book details
Book preview
Table of contents
Citations

About This Book

Explore the necessary concepts of REST API development by building few real world services from scratch.

Key Features

  • Follow best practices and explore techniques such as clustering and caching to achieve a reactive, scalable web service
  • Leverage the Gin Framework to quickly implement RESTful endpoints
  • Learn to implement a client library for a RESTful web service using Go

Book Description

REST is an architectural style that tackles the challenges of building scalable web services and in today's connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs. The depth, breadth, and ease of use of Go, makes it a breeze for developers to work with it to build robust Web APIs. This book takes you through the design of RESTful web services and leverages a framework like Gin

to implement these services.

The book starts with a brief introduction to REST API development and how it transformed the modern web. You will learn how to handle routing and authentication of web services along with working with middleware for internal service. The book explains how to use Go frameworks to build RESTful web services and work with MongoDB to create REST API. You will learn how to integrate Postgres SQL and JSON with a Go web service and build a client library in Go for consuming REST API. You will learn how to scale APIs using the microservice architecture and deploy the REST APIs using Nginx as a proxy server. Finally you will learn how to metricize a REST API using an API Gateway.

By the end of the book you will be proficient in building RESTful APIs in Go.

What you will learn

  • Create HTTP handler and introspect the Gorilla Mux router
  • OAuth 2 implementation with Go
  • Build RESTFul API with Gin Framework
  • Create REST API with MongoDB and Go
  • Build a working client library and unit test for REST API
  • Debug, test, and profile RESTful APIs with each of the frameworks
  • Optimize and scale REST API using microservices

Who this book is for

This book is intended for those who want to learn to build RESTful web services with a framework like Gin. To make best use of the code samples included in the book, you should have a basic knowledge of Go programming.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Building RESTful Web services with Go an online PDF/ePUB?
Yes, you can access Building RESTful Web services with Go by Naren Yellavula, Anshul Joshi in PDF and/or ePUB format, as well as other popular books in Ciencia de la computación & Programación en C#. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781788291088

Simplifying RESTful Services with Popular Go Frameworks

In this chapter, we are going to cover topics related to using a framework for simplifying building REST services. First, we will take a quick look at go-restful, a REST API creation framework, and then move on to a framework called Gin. We will try to build a Metro Rail API in this chapter. The frameworks we are about to discuss are fully-fledged web frameworks which can also be used to create REST APIs in a short time. We will talk a lot about resources and REST verbs in this chapter. We will try to integrate a small database called Sqlite3 with our API. Finally, we will inspect Revel.go and see how to prototype our REST API with it.
Overall, the topics we will cover in this chapter are as follows:
  • How to use SQLite3 in Go
  • Creating a REST API with the go-restful package
  • Introducing the Gin framework for creating a REST API
  • Introducing Revel.go for creating a REST API
  • Basics for building CRUD operations

Getting the code

You can get the code samples for this chapter from https://github.com/narenaryan/gorestful/tree/master/chapter4. This chapter's examples are in the form of a project instead of single programs. So, copy the respective directory to your GOPATH to run the code samples properly.

go-restful, a framework for REST API creation

go-restful is a package for building REST-style web services in Go. REST, as we discussed in the preceding section, asks developers to follow a set of design protocols. We have already discussed how the REST verbs should be defined and what they do to the resources.
Using go-restful, we can separate the logic for API handlers and attach REST verbs. The benefit of this is that it clearly tells us by looking at the code what API we are creating. Before jumping into an example, we need to install a database called SQLite3 for our REST API with go-restful. The installation steps are as follows:
  • On Ubuntu, run this command:
 apt-get install sqlite3 libsqlite3-dev
  • On OS X, you can use the brew command to install SQLite3:
 brew install sqlite3
  • Now, install the go-restful package with the following get command:
 go get github.com/emicklei/go-restful
We are ready to go. First, let us write a simple program showing what go-restful can do in a few lines of code. Let us create a simple ping server that echoes the server time back to the client:
package main
import (
"fmt"
"github.com/emicklei/go-restful"
"io"
"net/http"
"time"
)
func main() {
// Create a web service
webservice := new(restful.WebService)
// Create a route and attach it to handler in the service
webservice.Route(webservice.GET("/ping").To(pingTime))
// Add the service to application
restful.Add(webservice)
http.ListenAndServe(":8000", nil)
}
func pingTime(req *restful.Request, resp *restful.Response) {
// Write to the response
io.WriteString(resp, fmt.Sprintf("%s", time.Now()))
}
If we run this program:
go run basicExample.go
The server will be running on port 8000 of localhost. So, we can either make a curl request or use a browser to see the GET request output:
curl -X GET "http://localhost:8000/ping"
2017-06-06 07:37:26.238146296 +0530 IST
In the preceding program, we imported the go-restful library and we created a new service using a new instance of the restful.WebService struct. Next, we can create a REST verb using the following statement:
webservice.GET("/ping")
We can attach a function handler to execute this verb; pingTime is one such function. These chained functions are passed to a Route function to create a router. Then comes the following important statement:
restful.Add(webservice)
This registers the newly created webservice with the go-restful. If you observe, we are not passing any ServeMux objects to the http.ListenServe function; go-restful will take care of it. The main concept here is to use the resource-based REST API creation in go-restful. Going from the basic example, let us build something practical.
Take a scenario where your city is getting a new Metro Rail and you need to develop a REST API for other developers to consume and create an app accordingly. We will create one such API in this chapter and use various frameworks to show the implementation. Before that, for Create, Read, Update, Delete (CRUD) operations, we should know how to query or insert them into the SQLite DB with Go code.

CRUD operations and SQLite3 basics

All SQLite3 operations are going to be done using a library called go-sqlite3. We can install that package using the following command:
go get github.com/mattn/go-sqlite3
The special thing about this library is that it uses the internal sql package of Go. We usually import database/sql and use sql to execute database queries on the database (here, SQLite3):
import "database/sql"
Now, we can create a database driver and then execute the SQL commands on it using a method called Query:
sqliteFundamentals.go:
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
// Book is a placeholder for book
type Book struct {
id int
name string
author string
}
func main() {
db, err := sql.Open("sqlite3", "./books.db")
log.Println(db)
if err != nil {
log.Println(err)
}
// Create table
statement, err := db.Prepare("CREATE TABLE IF NOT EXISTS books (id
INTEGER PRIMARY KEY, isbn INTEGER, author VARCHAR(64), name VARCHAR(64) NULL)")
if err != nil {
log.Println("Error in creating table")
} else {
log.Println("Successfully created table books!")
}
statement.Exec()
// Create
statement, _ = db.Prepare("INSERT INTO books (name, author, isbn) VALUES (?, ?, ?)")
statement.Exec("A Tale of Two Cities", "Charles Dickens", 140430547)
log.Println("Inserted the book into database!")
// Read
rows, _ := db.Query("SELECT id, name, author FROM books")
var tempBook Book
for rows.Next() {
rows.Scan(&tempBook.id, &tempBook.name, &tempBook.author)
log.Printf("ID:%d, Book:%s, Author:%s\n", tempBook.id,
tempBook.name, tempBook.author)
}
// Update
statement, _ = db.Prepare("update books set name=? where id=?")
statement.Exec("The Tale of Two Cities", 1)
log.Println("Successfully updated the book in database!")
//Delete
statement, _ = db.Prepare("delete from books where id=?")
statement.Exec(1)
log.Println("Successfully deleted the book in database!")
}
This program explains how we can perform CRUD operations on a SQL database. Currently, the database is SQLite3. Let us run this using the following command:
go run sqliteFundamentals.go
And the output looks like the following, printing all the log statements:
2017/06/10 08:04:31 Successfully created table books!
2017/06/10 08:04:31 Inserted the book into database!
2017/06/10 08:04:31 ID:1, Book:A Tale of Two Cities, Author:Charles Dickens
2017/06/10 08:04:31 Successfully updated the book in database!
2017/06/10 08:04:31 Successfu...

Table of contents