70,79 €
Build real-world, production-ready solutions by harnessing the powerful features of Go
This book is intended for developers who are new to Go, but have previous experience of building web applications and APIs.
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library.
This course starts with a walkthrough of the topics most critical to anyone building a new web application. Whether it's keeping your application secure, connecting to your database, enabling token-based authentication, or utilizing logic-less templates, this course has you covered.
Scale, performance, and high availability lie at the heart of the projects, and the lessons learned throughout this course will arm you with everything you need to build world-class solutions. It will also take you through the history of concurrency, how Go utilizes it, how Go differs from other languages, and the features and structures of Go's concurrency core. It will make you feel comfortable designing a safe, data-consistent, and high-performance concurrent application in Go.
This course is an invaluable resource to help you understand Go's powerful features to build simple, reliable, secure, and efficient web applications.
This course is a step-by-step guide, which starts off with the basics of go programming to build web applications and will gradually move on to cover intermediate and advanced topics. You will be going through this smooth transition by building interesting projects along with the authors, discussing significant options, and decisions at each stage, while keeping the programs lean, uncluttered, and as simple as possible.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 794
Veröffentlichungsjahr: 2016
Build real-world, production-ready solutions by harnessing the powerful features of Go
A course in three modules
BIRMINGHAM - MUMBAI
Copyright © 2016 Packt Publishing
All rights reserved. No part of this course 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 course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, 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 course.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Published on: August 2016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78712-349-6
www.packtpub.com
Authors
Nathan Kozyra
Mat Ryer
Reviewers
Karthik Nayak
Tyler Bunnell
Michael Hamrah
Nimish Parmar
Jeremy R. Budnack
János Fehér
Aleksandar S. Sokolovski
Michele Della Torre
Content Development Editor
Arun Nadar
Graphics
Abhinash Sahu
Production Coordinator
Melwyn D'sa
Since the late 1980s and early 1990s, there has been a slow flood of powerful new languages and paradigms—Perl, Python, Ruby, PHP, and JavaScript—have taken an expanding user base by storm and has become one of the most popular languages (up there with stalwarts such as C, C++, and Java). Multithreading, memory caching, and APIs have allowed multiple processes, dissonant languages, applications, and even separate operating systems to work in congress.
And while this is great, there's a niche that until very recently was largely unserved: powerful, compiled, cross-platform languages with concurrency support that are geared towards systems programmers.
So when Google announced Go in 2009, which included some of the best minds in language design (and programming in general)—Rob Pike and Ken Thompson of Bell Labs fame and Robert Griesemer, who worked on Google's JavaScript implementation V8—to design a modern, concurrent language with development ease at the forefront.
For Go programming bright future, the team focused on some sore spots in the alternatives, which are as follows:
Module 1, Learning Go Web Development, starts off with introducing and setting up Go before you move on to produce responsive servers that react to certain web endpoint. You will then implement database connections to acquire data and then present it to our users using different template packages. Later on, you will learn about sessions and cookies to retain information before delving with the basics of microservices. By the end of this module, we will be covering the testing, debugging, and the security aspect.
Module 2, Go Programming Blueprints, has a project-based approach where you will be building chat application, adding authentication, and adding your own profile pictures in different ways. You will learn how Go makes it easy to build powerful command-line tools to find domain names before building a highly scalable Twitter polling and vote counting engine powered by NSQ and MongoDB. Later on it covers the functionalities of RESTful Data Web Service API and Google Places API before you move on to build a simple but powerful filesystem backup tool for our code projects.
Module 3, Mastering Concurrency in Go, introduces you to Concurrency in Go where you will be understanding the Concurrency model and developing a strategy for designing applications. You will learn to create basic and complex communication channels between our goroutines to manage data not only across single or multithreaded systems but also distributed systems. Later on you will be tackling a real-world problem, that is, being able to develop a high performance web server that can handle a very large volume of live, active traffic. You will then learn how to scale your application and make it capable of being expanded in scope, design, and/or capacity. It will then focus on when and where to implement concurrent patterns, utilize parallelism, and ensure data consistency. At the end of this module, we will be logging and testing concurrency before we finally look at the best practices on how to implement complicated and advanced techniques offered by Go.
For this course, any modern computers running a standard Linux flavor, OS X or Windows should be enough to get started. You can find a full list of requirements at https://golang.org/dl/. Later on, you'll also need to have the following software installed:
Your choice of IDE is a matter of personal preference.
This course is intended for developers who are new to Go but have previous experience of building web applications and APIs. It is also targeted towards systems or network programmer with some knowledge of Go and concurrency, but would like to know about the implementation of concurrent systems written in Go
Feedback from our readers is always welcome. Let us know what you think about this course—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 <[email protected]>, and mention the course'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.
Now that you are the proud owner of a Packt course, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this course from your account at http://www.packtpub.com. If you purchased this course elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the course's webpage at the Packt Publishing website. This page can be accessed by entering the course'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:
The code bundle for the course is also hosted on GitHub at https://github.com/PacktPublishing/repository-name. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 courses—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 course. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your course, 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 course in the search field. The required information will appear under the Errata section.
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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this course, you can contact us at <[email protected]>, and we will do our best to address the problem.
Learning Go Web Development
Build frontend-to-backend web applications using the best practices of a powerful, fast, and easy-to-deploy server language
When starting with Go, one of the most common things you'll hear being said is that it's a systems language.
Indeed, one of the earlier descriptions of Go, by the Go team itself, was that the language was built to be a modern systems language. It was constructed to combine the speed and power of languages, such as C with the syntactical elegance and thrift of modern interpreted languages, such as Python. You can see that goal realized when you look at just a few snippets of Go code.
From the Go FAQ on why Go was created:
"Go was born out of frustration with existing languages and environments for systems programming."
Perhaps the largest part of present-day Systems programming is designing backend servers. Obviously, the Web comprises a huge, but not exclusive, percentage of that world.
Go hasn't been considered a web language until recently. Unsurprisingly, it took a few years of developers dabbling, experimenting, and finally embracing the language to start taking it to new avenues.
While Go is web-ready out of the box, it lacks a lot of the critical frameworks and tools people so often take for granted with web development now. As the community around Go grew, the scaffolding began to manifest in a lot of new and exciting ways. Combined with existing ancillary tools, Go is now a wholly viable option for end-to-end web development. But back to that primary question: Why Go? To be fair, it's not right for every web project, but any application that can benefit from high-performance, secure web-serving out of the box with the added benefits of a beautiful concurrency model would make for a good candidate.
In this book, we're going to explore those aspects and others to outline what can make Go the right language for your web architecture and applications.
We're not going to deal with a lot of the low-level aspects of the Go language. For example, we assume you're familiar with variable and constant declaration. We assume you understand control structures.
In this chapter we will cover the following topics:
The most critical first step is, of course, making sure that Go is available and ready to start our first web server.
While one of Go's biggest selling points is its cross-platform support (both building and using locally while targeting other operating systems), your life will be much easier on a Nix compatible platform.
If you're on Windows, don't fear. Natively, you may run into incompatible packages, firewall issues when running using go run command and some other quirks, but 95% of the Go ecosystem will be available to you. You can also, very easily, run a virtual machine, and in fact that is a great way to simulate a potential production environment.
In-depth installation instructions are available at https://golang.org/doc/install, but we'll talk about a few quirky points here before moving on.
For OS X and Windows, Go is provided as a part of a binary installation package. For any Linux platform with a package manager, things can be pretty easy.
To install via common Linux package managers:
Ubuntu: sudo apt-get golang
CentOS: sudo yum install golang
On both OS X and Linux, you'll need to add a couple of lines to your path—the GOPATH and PATH. First, you'll want to find the location of your Go binary's installation. This varies from distribution to distribution. Once you've found that, you can configure the PATH and GOPATH, as follows:
While the path to be used is not defined rigidly, some convention has coalesced around starting at a subdirectory directly under your user's home directory, such as $HOME/go or ~Home/go. As long as this location is set perpetually and doesn't change, you won't run into issues with conflicts or missing packages.
You can test the impact of these changes by running the go env command. If you see any issues with this, it means that your directories are not correct.
Note that this may not prevent Go from running—depending on whether the GOBIN directory is properly set—but will prevent you from installing packages globally across your system.
To test the installation, you can grab any Go package by a go get command and create a Go file somewhere. As a quick example, first get a package at random, we'll use a package from the Gorilla framework, as we'll use this quite a bit throughout this book.
If this runs without any issue, Go is finding your GOPATH correctly. To make sure that Go is able to access your downloaded packages, draw up a very quick package that will attempt to utilize Gorilla's mux package and run it to verify whether the packages are found.
Run go run test.go in the command line. It won't do much, but it will deliver the good news as shown in the following screenshot:
Beyond the absolute and the most trivial application—one that cannot even produce a Hello World output—you must have some imported package in a Go application.
To say Hello World, for example, we'd need some sort of a way to generate an output. Unlike in many other languages, even the core language library is accessible by a namespaced package. In Go, namespaces are handled by a repository endpoint URL, which is github.com/nkozyra/gotest, which can be opened directly on GitHub (or any other public location) for the review.
The go get tool easily handles packages hosted at the repositories, such as GitHub, Bitbucket, and Google Code (as well as a few others). You can also host your own projects, ideally a git project, elsewhere, although it might introduce some dependencies and sources for errors, which you'd probably like to avoid.
But what about the private repos? While go get is a wonderful tool, you'll find yourself looking at an error without some additional configuration, SSH agent forwarding, and so on.
You can work around this in a couple of ways, but one very simple method is to clone the repository locally, using your version control software directly.
You may have paused when you read about the way namespaces are defined and imported in a Go application. What happens if you're using version 1 of the application but would like to bring in version 2? In most cases, this has to be explicitly defined in the path of the import. For example:
versus:
As you might imagine, this can be a particularly sticky aspect of the way Go handles the remote packages.
Unlike a lot of other package managers, go get is decentralized—that is, nobody maintains a canonical reference library of packages and versions. This can sometimes be a sore spot for new developers.
For the most part, packages are always imported via the go get command, which reads the master branch of the remote repository. This means that maintaining multiple versions of a package at the same endpoint is, for the most part, impossible.
It's the utilization of the URL endpoints as namespaces that allows the decentralization, but it's also what provides a lack of internal support for versioning.
Your best bet as a developer is to treat every package as the most up-to-date version when you perform a go get command. If you need a newer version, you can always follow whatever pattern the author has decided on, such as the preceding example.
As a creator of your own packages, make sure that you also adhere to this philosophy. Keeping your master branch HEAD as the most up-to-date will make sure your that the code fits with the conventions of other Go authors.
At the heart of all network communications in Go is the aptly-named net package, which contains subpackages not only for the very relevant HTTP operations, but also for other TCP/UDP servers, DNS, and IP tools.
In short, everything you need to create a robust server environment.
Of course, what we care about for the purpose of this book lies primarily in the net/http package, but we'll look at a few other functions that utilize the rest of the package, such as a TCP connection, as well as WebSockets.
Let's quickly take a look at just performing that Hello World (or Web, in this case) example we have been talking about.
This chapter serves as an introduction to the most basic concepts of Go and producing for the Web in Go, but these points are critical foundational elements for being productive in the language and in the community.
We've looked at coding conventions and package design and organization, and we've produced our first program—the all-too-familiar Hello, World application—and accessed it via our localhost.
Obviously, we're a long way from a real, mature application for the Web, but the building blocks are essential to getting there.
In Chapter 2, Serving and Routing, we'll look at how to direct different requests to different application logic using the built-in routing functionality in Go's net/http package, as well as a couple of third party router packages.
In Chapter 1, Introducing and Setting Up, we produced a very basic URL endpoint that allowed static file serving.
The following are the simple routes we produced for that example:
In review, you can see two endpoints, /static and /, which either serve a single static file or generate output to the http.ResponseWriter.
We can have any number of routers sitting side by side. However, consider a scenario where we have a basic website with about, contact, and staff pages, with each residing in /var/www/about/index.html, /var/www/contact.html, and /var/www/staff/home.html. While it's an intentionally obtuse example, it demonstrates the limitations of Go's built-in and unmodified routing system. We cannot route all requests to the same directory locally, we need something that provides more malleable URLs.
Before we look at simple and incredibly common errors like 404s, let's address the idea of redirecting requests, something that's very common. Although not always for reasons that are evident or tangible for the average user.
So we might we want to redirect requests to another request? Well there are quite a few reasons, as defined by the HTTP specification that could lead us to implement automatic redirects on any given request. Here are a few of them with their corresponding HTTP status codes:
Executing any one of these is incredibly simple in basic Go with net/http, but as you might expect, it is facilitated and improved with more robust frameworks, such as Gorilla.
We can now produce not only the basic routes from the net/http package but more complicated ones using the Gorilla toolkit. By utilizing Gorilla, we can now create regular expressions and implement pattern-based routing and allow much more flexibility to our routing patterns.
With this increased flexibility, we also have to be mindful of errors now, so we've looked at handling error-based redirects and messages, including a custom 404, Page not found message to produce more customized error messages.
Now that we have the basics down for creating endpoints, routes, and handlers; we need to start doing some non-trivial data serving.
In Chapter 3, Connecting to Data, we'll start getting dynamic information from databases, so we can manage data in a smarter and more reliable fashion. By connecting to a couple of different, commonly-used databases, we'll be able to build robust, dynamic, and scalable web applications.
