Previous Next

Building RESTful Web services with Go Learn how to build powerful RESTful APIs with Golang that scale gracefully (Naren Yellavula) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Naren Yellavula

Web

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 u

📄 File Format: PDF
💾 File Size: 4.3 MB
11
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (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 Naren Yellavula BIRMINGHAM - MUMBAI
📄 Page 3
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. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78829-428-7 www.packtpub.com
📄 Page 4
Credits Author Naren Yellavula Copy Editors Dhanya Baburaj Safis Editing Reviewer Anshul Joshi Project Coordinator Sheejal Shah Commissioning Editor Aaron Lazar Proofreader Safis Editing Acquisition Editor Denim Pinto Indexer Rekha Nair Content Development Editor Sreeja Nair Graphics Jason Monteiro Technical Editor Rutuja Vaze Production Coordinator Nilesh Mohite
📄 Page 5
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 6
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 7
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 8
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. 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 9
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 10
Table of Contents Preface 1 Chapter 1: Getting Started with REST API Development 7 Types of web services 8 REST API 9 Characteristics of REST services 10 REST verbs and status codes 11 GET 13 POST, PUT, and PATCH 14 DELETE and OPTIONS 15 Cross-Origin Resource Sharing (CORS) 16 Types of status codes 17 2xx family (successful) 18 3xx family (redirection) 18 4xx family (client error) 18 5xx family (server error) 19 Rise of REST API with Single Page Applications 19 Old and new ways of data flow in SPA 20 Why Go for REST API development? 22 Setting up the project and running the development server 22 Demystifying GOPATH 23 Building our first service – finding the Roman numeral 25 Breaking down the code 29 Live reloading the application with supervisord and Gulp 30 Monitoring your Go web server with supervisord 30 Installing supervisord 30 Using Gulp for creating auto code compiling and server reloading 32 Understanding the gulpfile 34 Summary 35 Chapter 2: Handling Routing for Our REST Services 36 Getting the code 37 Understanding Go's net/http package 37 Running the code 38 ServeMux, a basic router in Go 38 Running the code 40 Adding multiple handlers using ServeMux 40
📄 Page 11
Table of Contents [ ii ] Running the code 41 Introducing httprouter, a lightweight HTTP router 42 Installation 42 Program explanation 44 Building the simple static file server in minutes 46 Introducing Gorilla Mux, a powerful HTTP router 47 Installation 48 Fundamentals of Gorilla Mux 48 Reverse mapping URL 50 Custom paths 50 Path Prefix 51 Strict Slash 51 Encoded paths 52 Query-based matching 52 Host-based matching 53 SQL injections in URLs and ways to avoid them 55 Creating a basic API layout for URL shortening services 56 Summary 57 Chapter 3: Working with Middleware and RPC 58 Getting the code 58 What is middleware? 59 Creating a basic middleware 60 Multiple middleware and chaining 63 Painless middleware chaining with Alice 69 Using Gorilla's Handlers middleware for Logging 70 What is RPC? 72 Creating an RPC server 73 Creating an RPC client 74 JSON RPC using Gorilla RPC 76 Summary 79 Chapter 4: Simplifying RESTful Services with Popular Go Frameworks 80 Getting the code 80 go-restful, a framework for REST API creation 81 CRUD operations and SQLite3 basics 83 Building a Metro Rail API with go-restful 85 Design specification 86 Creating database models 86 Building RESTful APIs with the Gin framework 96 Building a RESTful API with Revel.go 102
📄 Page 12
Table of Contents [ iii ] Summary 107 Chapter 5: Working with MongoDB and Go to Create REST APIs 109 Getting the code 109 Introduction to MongoDB 110 Installing MongoDB and using the shell 110 Working with the Mongo shell 112 Introducing mgo, a MongoDB driver for Go 117 RESTful API with Gorilla Mux and MongoDB 120 Boosting the querying performance with indexing 125 Designing an e-commerce data document model 128 Summary 131 Chapter 6: Working with Protocol Buffers and GRPC 132 Getting the code 132 Introduction to protocol buffers 133 Protocol buffer language 134 Scalar values 135 Enumerations and repeated fields 136 Compiling a protocol buffer with protoc 138 Introduction to GRPC 144 Bidirectional streaming with GRPC 151 Summary 156 Chapter 7: Working with PostgreSQL, JSON, and Go 158 Getting the code 158 Installing the PostgreSQL database 159 Adding users and databases in PostgreSQL 160 pq, a pure PostgreSQL database driver for Go 162 Implementing a URL shortening service using Postgres and pq 165 Defining the Base62 algorithm 165 Exploring the JSON store in PostgreSQL 172 GORM, a powerful ORM for Go 172 Implementing the e-commerce REST API 174 Summary 180 Chapter 8: Building a REST API Client in Go and Unit Testing 181 Getting the code 182 Plan for building a REST API client 182 Basics for writing a command-line tool in Go 182 CLI – a library for building beautiful clients 186
📄 Page 13
Table of Contents [ iv ] Collecting command-line arguments in CLI 188 grequests – a REST API package for Go 191 API overview of grequests 192 Getting comfortable with the GitHub REST API 193 Creating a CLI tool as an API client for the GitHub REST API 196 Using Redis for caching the API data 201 Creating a unit testing tool for our URL shortening service 203 Summary 204 Chapter 9: Scaling Our REST API Using Microservices 205 Getting the code 206 What are microservices? 206 Monolith versus microservices 208 Go Kit, a package for building microservices 209 Building a REST microservice with Go Kit 212 Adding logging to your microservice 219 Adding instrumentation to your microservice 222 Summary 228 Chapter 10: Deploying Our REST services 229 Getting the code 229 Installing and configuring Nginx 230 What is a proxy server? 231 Important Nginx paths 233 Using server blocks 234 Creating a sample Go application and proxying it 234 Load balancing with Nginx 238 Rate limiting our REST API 240 Securing our Nginx proxy server 242 Monitoring our Go API server with Supervisord 243 Installing Supervisord 243 Summary 245 Chapter 11: Using an API Gateway to Monitor and Metricize REST API 247 Getting the code 248 Why is an API gateway required? 248 Kong, an open-source API gateway 250 Introducing Docker 251 Installing a Kong database and Kong 252 Adding API to Kong 255 API logging in Kong 258
📄 Page 14
Table of Contents [ v ] API authentication in Kong 260 API rate limiting in Kong 263 Kong CLI 265 Other API gateways 266 Summary 266 Chapter 12: Handling Authentication for Our REST Services 267 Getting the code 267 How authentication works 268 Session-based authentication 269 Introducing Postman, a tool for testing REST API 273 Persisting client sessions with Redis 275 Introduction to JSON Web Tokens (JWT) and OAuth2 279 JSON web token format 281 Reserved claims 282 Private claims 282 Creating a JWT in Go 283 Reading a JWT in Go 284 OAuth 2 architecture and basics 285 Authentication versus authorization 285 Summary 292 Index 293
📄 Page 15
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/ ​golang/ ​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. 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.
📄 Page 16
Preface [ 2 ] 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). What you need for this book For this book, you need a laptop/PC with Linux (Ubuntu 16.04), macOS X, or Windows installed. We will use Go 1.8+ as the version of our compiler and install many third-party packages, so a working internet connection is required. We will also use Docker in the final chapters to explain concepts of API Gateway. Docker V17.0+ is recommended. If Windows users have problems with the native Go installation for any examples, use Docker for Windows and run Ubuntu container, which gives more flexibility; refer to https:/ ​/ ​www. ​docker. ​com/​docker- ​windows for more details.
📄 Page 17
Preface [ 3 ] Before diving into the book, refresh your language basics at https:/ ​/​tour. ​golang. ​org/ welcome/​1. Even though these are the basic requirements, we will guide you through the installations wherever required. Who this book is for This book is for all the Go developers who are comfortable with the language and seeking to learn REST API development. Even senior engineers can enjoy this book, as it has many cutting-edge concepts, such as microservices, protocol buffers, and gRPC. Developers who are already familiar with REST concepts and stepping into the Go world from other platforms, such as Python and Ruby, can also benefit a lot. Conventions In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Name the preceding program as basicHandler.go." A block of code is set as follows: { "ID": 1, "DriverName": "Menaka", "OperatingStatus": true } Any command-line input or output is written as follows: go run customMux.go
📄 Page 18
Preface [ 4 ] New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "It returns message saying Logged In successfully." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors . Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for this book from your account at http:/ ​/​www. packtpub.​com. If you purchased this book elsewhere, you can visit http:/ ​/​www. ​packtpub. com/​support and register to have the files e-mailed directly to you.
📄 Page 19
Preface [ 5 ] You can download the code files by following these steps: Log in or register to our website using your e-mail address and password.1. Hover the mouse pointer on the SUPPORT tab at the top.2. Click on Code Downloads & Errata.3. Enter the name of the book in the Search box.4. Select the book for which you're looking to download the code files.5. Choose from the drop-down menu where you purchased this book from.6. Click on Code Download.7. You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: WinRAR / 7-Zip for Windows Zipeg / iZip / UnRarX for Mac 7-Zip / PeaZip for Linux The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-RESTful-Web-Services-with-Go. We also have other code bundles from our rich catalog of books and videos available at https:/ /​github.​com/​PacktPublishing/ ​. Check them out! Downloading the color images of this book We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https:/ ​/ ​www. ​packtpub. ​com/ ​sites/ ​default/ ​files/ downloads/​BuildingRESTfulWebServiceswithGo_ ​ColorImages. ​pdf.
📄 Page 20
Preface [ 6 ] Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code- we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http:/ ​/​www. ​packtpub. ​com/ ​submit- ​errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https:/ ​/​www. ​packtpub. ​com/ ​books/ content/​support and enter the name of the book in the search field. The required information will appear under the Errata section. Piracy Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

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