
- 338 pages
- English
- ePUB (mobile friendly)
- Available on iOS & Android
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
- 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.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Information
Writing and Consuming RESTful Web Services in Go
- 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
Creating your first HTTP GET method
How to do it...
- Install the github.com/gorilla/mux package using the go get command, as follows:
$ go get github.com/gorilla/mux
- 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
}
}
- Run the program with the following command:
$ go run http-rest-get.go
How it works...
$ curl -X GET http://localhost:8080/employees
[{"id":"1","firstName":"Foo","lastName":"Bar"},{"id":"2","firstName":"Baz","lastName":"Qux"}]
$ curl -X GET http://localhost:8080/employee/1
{"id":"1","firstName":"Foo","lastName":"Bar"}
- 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.
- 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.
- 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,
},
}
- Next, we defined a static Employees array, as follows:
func init()
{
employees = Employees
{
Employee{Id: "1", FirstName: "Foo", LastNam...
Table of contents
- Title Page
- Copyright and Credits
- Dedication
- Packt Upsell
- Contributors
- Preface
- Creating Your First Server in Go
- Working with Templates, Static Files, and HTML Forms
- Working with Sessions, Error Handling, and Caching in Go
- Writing and Consuming RESTful Web Services in Go
- Working with SQL and NoSQL Databases
- Writing Microservices in Go Using Micro – a Microservice Toolkit
- Working with WebSocket in Go
- Working with the Go Web Application Framework – Beego
- Working with Go and Docker
- Securing a Go Web Application
- Deploying a Go Web App and Docker Containers to AWS
- Other Books You May Enjoy