Go Web Development Cookbook
eBook - ePub

Go Web Development Cookbook

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

Go Web Development Cookbook

About this book

86 recipes on how to build fast, scalable, and powerful web services and applications with GoAbout This Book• Become proficient in RESTful web services• Build scalable, high-performant web applications in Go• Get acquainted with Go frameworks for web developmentWho This Book Is ForThis book is for Go developers interested in learning how to use Go to build powerful web applications. A background in web development is expected.What You Will Learn• Create a simple HTTP and TCP web server and understand how it works• Explore record in a MySQL and MongoDB database• Write and consume RESTful web service in Go• Invent microservices in Go using Micro – a microservice toolkit• Create and Deploy the Beego application with Nginx• Deploy Go web application and Docker containers on an AWS EC2 instanceIn DetailGo 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.Style and approachThis book helps you learn core Go concepts faster by taking a recipe-based approach.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
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.
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.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Go Web Development Cookbook by Arpit Aggarwal in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming Languages. We have over one million books available in our catalogue for you to explore.

Information

Writing and Consuming RESTful Web Services in Go

In this chapter, we will cover the following recipes:
  • Creating your first HTTP GET method
  • Creating your first HTTP POST method
  • Creating your first HTTP PUT method
  • Creating your first HTTP DELETE method
  • Versioning your REST API
  • Creating your first REST client
  • Creating your first AngularJS client
  • Creating your first ReactJS client
  • Creating your first VueJS client

Introduction

Whenever we build a web application that encapsulates logic that could be helpful to other related applications, we will often also write and consume web services. This is because they expose functionality over a network, which is accessible through the HTTP protocol, making an application a single source of truth.
In this chapter, we will write a RESTful API that supports GET, POST, PUT, and DELETE HTTP methods, and then we will learn how we can version the REST API, which is very helpful when we are creating APIs consumed publicly. We will finish up with writing the REST client to consume them.

Creating your first HTTP GET method

While writing web applications, we often have to expose our services to the client or to the UI so that they can consume a piece of code running on a different system. Exposing the service can be done with HTTP protocol methods. Out of the many HTTP methods, we will be learning to implement the HTTP GET method in this recipe.

How to do it...

  1. Install the github.com/gorilla/mux package using the go get command, as follows:
$ go get github.com/gorilla/mux
  1. Create http-rest-get.go where we will define two routes—/employees and /employee/{id} along with their handlers. The former writes the static array of employees and the latter writes employee details for the provided ID to an HTTP response stream, as follows:
package main
import
(
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Route struct
{
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes
{
Route
{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route
{
"getEmployee",
"GET",
"/employee/{id}",
getEmployee,
},
}
type Employee struct
{
Id string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Employees []Employee
var employees []Employee
func init()
{
employees = Employees
{
Employee{Id: "1", FirstName: "Foo", LastName: "Bar"},
Employee{Id: "2", FirstName: "Baz", LastName: "Qux"},
}
}
func getEmployees(w http.ResponseWriter, r *http.Request)
{
json.NewEncoder(w).Encode(employees)
}
func getEmployee(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
id := vars["id"]
for _, employee := range employees
{
if employee.Id == id
{
if err := json.NewEncoder(w).Encode(employee); err != nil
{
log.Print("error getting requested employee :: ", err)
}
}
}
}
func AddRoutes(router *mux.Router) *mux.Router
{
for _, route := range routes
{
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
func main()
{
muxRouter := mux.NewRouter().StrictSlash(true)
router := AddRoutes(muxRouter)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil
{
log.Fatal("error starting http server :: ", err)
return
}
}
  1. Run the program with the following command:
$ go run http-rest-get.go

How it works...

Once we run the program, the HTTP server will start locally listening on port 8080.
Next, executing a GET request from the command line as follows will give you a list of all the employees:
$ curl -X GET http://localhost:8080/employees
[{"id":"1","firstName":"Foo","lastName":"Bar"},{"id":"2","firstName":"Baz","lastName":"Qux"}]
Here, executing a GET request for a particular employee ID from the command line as follows, will give you the employee details for the corresponding ID:
$ curl -X GET http://localhost:8080/employee/1
{"id":"1","firstName":"Foo","lastName":"Bar"}
Let’s understand the program we have written:
  1. We used import ("encoding/json" "log" "net/http" "strconv" "github.com/gorilla/mux"). Here, we imported github.com/gorilla/mux to create a Gorilla Mux Router.
  2. Next, we declared the Route struct type with four fields—Name, Method, Pattern, and HandlerFunc, where Name represents the name of an HTTP method, Method represents the HTTP method type which can be GET, POST, PUT, DELETE, and so on, Pattern represents the URL path, and HandlerFunc represents the HTTP handler.
  3. Next, we defined two routes for the GET request, as follows:
var routes = Routes
{
Route
{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route
{
"getEmployee",
"GET",
"/employee/{id}",
getEmployee,
},
}
  1. Next, we defined a static Employees array, as follows:
func init() 
{
employees = Employees
{
Employee{Id: "1", FirstName: "Foo", LastNam...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Creating Your First Server in Go
  8. Working with Templates, Static Files, and HTML Forms
  9. Working with Sessions, Error Handling, and Caching in Go
  10. Writing and Consuming RESTful Web Services in Go
  11. Working with SQL and NoSQL Databases
  12. Writing Microservices in Go Using Micro – a Microservice Toolkit
  13. Working with WebSocket in Go
  14. Working with the Go Web Application Framework – Beego
  15. Working with Go and Docker
  16. Securing a Go Web Application
  17. Deploying a Go Web App and Docker Containers to AWS
  18. Other Books You May Enjoy