Building RESTful Web services with Go
eBook - ePub

Building RESTful Web services with Go

Naren Yellavula, Anshul Joshi

Buch teilen
  1. 316 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Building RESTful Web services with Go

Naren Yellavula, Anshul Joshi

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Building RESTful Web services with Go als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Building RESTful Web services with Go von Naren Yellavula, Anshul Joshi im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatica & Programmazione in C#. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
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...

Inhaltsverzeichnis