Share E-Book

Building RESTful Web services with Go (Naren Yellavula)(Z-Library)

Author

Rating 3.5 AI initial rating

Log in to rate

Go
Language English

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

Format PDF
Size 5.1 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
Building RESTful Web Services with Go Learn how to build powerful RESTful APIs with Golang that scale gracefully
Page 3
Naren Yellavula BIRMINGHAM - MUMBAI
Page 4
Building RESTful Web Services with Go Copyright © 2017 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: December 2017 Production reference: 1261217 Published by Packt Publishing Ltd.
Page 5
Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78829-428-7 www.packtpub.com
Page 6
Credits Author Naren Yellavula Copy Editors Dhanya Baburaj Safis Editing Reviewer Anshul Joshi Project Coordinator Sheejal Shah Commissioning Editor Aaron Lazar Proofreader Safis Editing
Page 7
Acquisition Editor Denim Pinto Indexer Rekha Nair Content Development Editor Sreeja Nair Graphics Jason Monteiro Technical Editor Rutuja Vaze Production Coordinator Nilesh Mohite
Page 8
About the Author Naren Yellavula—fondly called by the developer community as Naren Arya— started his programming career in the funniest way. He ditched mechanical engineering for computer science after watching The Matrix for the first time. With dreams of coding a mini world, he continuously sharpened his practical skills. Initially, he built few a mobile applications. Then, he completely moved into the space of full stack development. He always believed that computers and software can help make this world a better place. He wrote 120+ development articles on various open source technologies, including Go and Python. He is also one of the few young speakers at the PyCon India conference (he spoke at Bangalore in 2015 and Delhi in 2017). With detailed knowledge of web scraping and REST APIs, he dived into multiple domains such as cloud telephony and cloud-based web services. On this journey, he bathed in a lot of design decisions. He currently works as a software engineer for Citrix R&D, India. Naren is a great fan of Go personally because of the speed and intuitiveness of the language. In his spare time, he tries to educate the youth in programming and software development. He loves reading nonfiction most of the time, and Victorian and Russian fiction sometimes.
Page 9
Acknowledgments I would like to thank my grandmother, Tayamma, for raising me to be helpful to others by sharing my knowledge in every possible way. She was the one who always taught me how to put in serious effort with 100% dedication, and not worry much about results. Therefore, I dedicate this book to her, to my inspiration. I also cannot understate the support given by my father, Venkataiah Yellavula; mother, ShobaRani Dasyam; and lovely younger brother Saikiran, who understood the value of the time I spent on this book and always encouraged me with their positive wishes. I am grateful to my mentor, Chandrashekar MuniBudha, Solutions Architect, Amazon Web Services, whom I am deeply indebted to. I also thank Ashwin Baskaran, Senior Director, Citrix, who encouraged and pushed me forward in all possible ways. Thank you! I cannot name everyone here; the list is so big. However, I sincerely thank all my friends who always wished success for this book.
Page 10
About the Reviewer Anshul Joshi is a data scientist with experience in recommendation systems, predictive modeling, neural networks, and high-performance computing. His research interests encompass deep learning, artificial intelligence, and computational physics. Most of the time, he can be found exploring GitHub or trying anything new he can get his hands on. His blog can be found at https://anshuljoshi.com/.
Page 11
www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Page 12
Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
Page 13
Customer Feedback Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788294289. If you'd like to join our team of regular reviewers, you can email us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Page 14
Table of Contents Preface What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the example code Downloading the color images of this book Errata Piracy Questions 1. Getting Started with REST API Development Types of web services REST API Characteristics of REST services REST verbs and status codes GET POST, PUT, and PATCH DELETE and OPTIONS Cross-Origin Resource Sharing (CORS) Types of status codes 2xx family (successful) 3xx family (redirection) 4xx family (client error) 5xx family (server error) Rise of REST API with Single Page Applications Old and new ways of data flow in SPA Why Go for REST API development? Setting up the project and running the development server Demystifying GOPATH Building our first service – finding the Roman numeral Breaking down the code Live reloading the application with supervisord and Gulp Monitoring your Go web server with supervisord Installing supervisord Using Gulp for creating auto code compiling and server reloading Understanding the gulpfile Summary 2. Handling Routing for Our REST Services Getting the code
Page 15
Understanding Go's net/http package Running the code ServeMux, a basic router in Go Running the code Adding multiple handlers using ServeMux Running the code Introducing httprouter, a lightweight HTTP router Installation Program explanation Building the simple static file server in minutes Introducing Gorilla Mux, a powerful HTTP router Installation Fundamentals of Gorilla Mux Reverse mapping URL Custom paths Path Prefix Strict Slash Encoded paths Query-based matching Host-based matching SQL injections in URLs and ways to avoid them Creating a basic API layout for URL shortening services Summary 3. Working with Middleware and RPC Getting the code What is middleware? Creating a basic middleware Multiple middleware and chaining Painless middleware chaining with Alice Using Gorilla's Handlers middleware for Logging What is RPC? Creating an RPC server Creating an RPC client JSON RPC using Gorilla RPC Summary 4. Simplifying RESTful Services with Popular Go Frameworks Getting the code go-restful, a framework for REST API creation CRUD operations and SQLite3 basics Building a Metro Rail API with go-restful Design specification Creating database models Building RESTful APIs with the Gin framework Building a RESTful API with Revel.go
Page 16
Summary 5. Working with MongoDB and Go to Create REST APIs Getting the code Introduction to MongoDB Installing MongoDB and using the shell Working with the Mongo shell Introducing mgo, a MongoDB driver for Go RESTful API with Gorilla Mux and MongoDB Boosting the querying performance with indexing Designing an e-commerce data document model Summary 6. Working with Protocol Buffers and GRPC Getting the code Introduction to protocol buffers Protocol buffer language Scalar values Enumerations and repeated fields Compiling a protocol buffer with protoc Introduction to GRPC Bidirectional streaming with GRPC Summary 7. Working with PostgreSQL, JSON, and Go Getting the code Installing the PostgreSQL database Adding users and databases in PostgreSQL pq, a pure PostgreSQL database driver for Go Implementing a URL shortening service using Postgres and pq Defining the Base62 algorithm Exploring the JSON store in PostgreSQL GORM, a powerful ORM for Go Implementing the e-commerce REST API Summary 8. Building a REST API Client in Go and Unit Testing Getting the code Plan for building a REST API client Basics for writing a command-line tool in Go CLI – a library for building beautiful clients Collecting command-line arguments in CLI grequests – a REST API package for Go API overview of grequests Getting comfortable with the GitHub REST API Creating a CLI tool as an API client for the GitHub REST API
Page 17
Using Redis for caching the API data Creating a unit testing tool for our URL shortening service Summary 9. Scaling Our REST API Using Microservices Getting the code What are microservices? Monolith versus microservices Go Kit, a package for building microservices Building a REST microservice with Go Kit Adding logging to your microservice Adding instrumentation to your microservice Summary 10. Deploying Our REST services Getting the code Installing and configuring Nginx What is a proxy server? Important Nginx paths Using server blocks Creating a sample Go application and proxying it Load balancing with Nginx Rate limiting our REST API Securing our Nginx proxy server Monitoring our Go API server with Supervisord Installing Supervisord Summary 11. Using an API Gateway to Monitor and Metricize REST API Getting the code Why is an API gateway required? Kong, an open-source API gateway Introducing Docker Installing a Kong database and Kong Adding API to Kong API logging in Kong API authentication in Kong API rate limiting in Kong Kong CLI Other API gateways Summary 12. Handling Authentication for Our REST Services Getting the code How authentication works Session-based authentication
Page 18
Introducing Postman, a tool for testing REST API Persisting client sessions with Redis Introduction to JSON Web Tokens (JWT) and OAuth2 JSON web token format Reserved claims Private claims Creating a JWT in Go Reading a JWT in Go OAuth 2 architecture and basics Authentication versus authorization Summary
Page 19
Preface Initially, SOAP-based web services became more popular with XML. Then, since 2012, REST picked up the pace and gulped SOAP in whole. The rise of a new generation of web languages, such as Python, JavaScript (Node.js), and Go, showed a different approach to web development compared to the traditional ones, such as ASP.NET and Spring. Since this decade, Go has become more and more popular due to its speed and intuitiveness. Less verbose code, strict type checking, and support for concurrency make Go a better choice for writing any web backend. Some of the best tools, such as Docker and Kubernetes, are written in Go. Google uses Go a lot in its daily activities. You can see a list of Go-using companies at https://github.com/gol ang/go/wiki/GoUsers. For any internet company, the web development department is crucial. Data that the company accumulates needs to be served to the clients in form of an API or web service. Various clients (browser, mobile application, and server) consume API every day. REST is an architectural pattern that defines resource consumption in the form of methods. Go is a better language to write web servers. It is the responsibility of an intermediate Go developer to know how to create RESTful services using the constructs available in the language. Once the basics are understood, the developer should learn other things, such as testing, optimizing, and deploying services. This book is an attempt to make the reader comfortable with developing web services. Experts think that in the near future, as Python is moving into the Data Science space and competing with R, Go can emerge as the single go-to language in the web development space by competing with NodeJS. This book is not a cookbook. However, it offers many tips and tricks throughout your journey. By the end of the book, the reader will be comfortable with REST API development through a multitude of examples. They will also come to know about the latest practices, such as protocol buffers/gRPC/API Gateway, which will move their knowledge to the next level.
Page 20
What this book covers Chapter 1, Getting Started with REST API Development, discusses the fundamentals of REST architecture and verbs. Chapter 2, Handling Routing for Our REST Services, describes how to add routing to our API. Chapter 3, Working with Middleware and RPC, is about working with middleware handlers and basic RPC. Chapter 4, Simplifying RESTful Services with Popular Go Frameworks, presents quick prototyping API with frameworks. Chapter 5, Working with MongoDB and Go to Create REST API, explains how to use MongoDB as the database for our API. Chapter 6, Working with Protocol Buffers and gRPC, shows how to use Protocol buffers and gRPC to obtain performance boost over HTTP/JSON. Chapter 7, Working with PostgreSQL, JSON, and Go, explains the benefits of PostgreSQL and a JSON store for creating APIs. Chapter 8, Building a REST API Client in Go and Unit Testing, presents techniques for building client software and API testing with unit tests in Go. Chapter 9, Scaling Our REST API Using Microservices, is about breaking our API service into microservices using Go Kit. Chapter 10, Deploying Our REST Services, shows how we can deploy services built on Nginx and monitor them using supervisord. Chapter 11, Using an API Gateway to Monitor and Metricize REST API, explains how to make our services production grade by adding multiple APIs behind API Gateway. Chapter 12, Handling Authentication for Our REST Services, discusses securing our API with basic authentication and JSON Web Tokens (JWT).
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List