Hands-On Full Stack Development with Go - Mina Andrawos - E-Book

Hands-On Full Stack Development with Go E-Book

Mina Andrawos

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Create a real-world application in Go and explore various frameworks and methodologies for full-stack development




Key Features



  • Build a responsive front end by using the powerful React framework


  • Build web APIs and middleware in the Go language by making use of the popular Gin framework


  • Build an Isomorphic Go React application via GopherJS


  • Perform unit tests, and benchmarking on your web API





Book Description



The Go programming language has been rapidly adopted by developers for building web applications. With its impressive performance and ease of development, Go enjoys the support of a wide variety of open source frameworks, for building scalable and high-performant web services and apps. Hands-On Full Stack Development with Go is a comprehensive guide that covers all aspects of full stack development with Go.







This clearly written, example-rich book begins with a practical exposure to Go development and moves on to build a frontend with the popular React framework. From there, you will build RESTful web APIs utilizing the Gin framework. After that, we will dive deeper into important software backend concepts, such as connecting to the database via an ORM, designing routes for your services, securing your services, and even charging credit cards via the popular Stripe API. We will also cover how to test, and benchmark your applications efficiently in a production environment. In the concluding chapters, we will cover isomorphic developments in pure Go by learning about GopherJS. As you progress through the book, you'll gradually build a musical instrument online store application from scratch.







By the end of the book, you will be confident in taking on full stack web applications in Go.




What you will learn





  • Understand Go programming by building a real-world application


  • Learn the React framework to develop a frontend for your application


  • Understand isomorphic web development utilizing the GopherJS framework


  • Explore methods to write RESTful web APIs in Go using the Gin framework


  • Learn practical topics such as ORM layers, secure communications, and Stripe's API


  • Learn methods to benchmark and test web APIs in Go



Who this book is for



Hands-On Full Stack Development with Go will appeal to developers who are looking to start building amazing full stack web applications in Go. Basic knowhow of Go language and JavaScript is expected. The book targets web developers who are looking to move to the Go language.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 325

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On Full Stack Development with Go

 

 

 

 

 

 

 

 

 

 

Build full stack web applications with Go, React, Gin, and GopherJS

 

 

 

 

 

 

 

 

 

 

 

 

 

Mina Andrawos

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Hands-On Full Stack Development with Go

Copyright © 2019 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

 

Commissioning Editor: Aaron LazarAcquisition Editor: Shahnish KhanContent Development Editor: Zeeyan PinheiroTechnical Editor:Sabaah NavlekarCopy Editor: Safis EditingProject Coordinator:Vaidehi SawantProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics:Alishon MendonsaProduction Coordinator:Jyoti Chauhan

First published: March 2019

Production reference: 1260319

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78913-075-1

www.packtpub.com

 
 
 
 
 
 
   
For Nabil, Mervat, Catherine, and Fady.  Thanks to all of my family for their amazing support and continuous encouragement.
– Mina Andrawos
 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.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.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.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. 

Contributors

About the author

Mina Andrawos is an experienced engineer who has acquired deep experience in Go from using it personally and professionally. He regularly authors articles and tutorials about the language, and also shares Go's open source projects. He has written numerous Go applications with varying degrees of complexity. Other than Go, he has skills in Java, C#, Python, and C++. Besides software development, he has working experience of scrum mastering, sales engineering, and software product management.

About the reviewer

Pankaj Khairnar is a founder and CEO of Scalent Infotech Pvt. Ltd. (a Golang-specialized development company.) In his career of over 12 years, he has developed many highly scalable platforms for various domains such as digital advertising, the Internet of Things (IoT), and e-commerce. Pankaj always likes to explore and implement new cutting-edge technologies.

I would like to thank Anant Haral for helping by re-reviewing all the chapters and testing all the examples again.

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Hands-On Full Stack Development with Go

Dedication

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Section 1: The Go Language

Welcome to Full Stack Go

What is full stack development?

What will we build?

The application architecture

The outline of this book

Building Blocks of the Go Language

Technical requirements

Go's playground

Setting up Go's workspace

Packages, variables, data types, and pointers

Packages

Variables and data types

Pointers

Functions and closures

Functions – the basics

Functions – accessing functions from other packages

Closures

Go data structures

Arrays

Slices

Maps

Struct

Methods

Type embedding

Interfaces

Conditional statements and loops

The if statement

The switch statement

Loops

Panics, recovers, and defers

Summary

Questions

Further reading

Go Concurrency

What is concurrency?

Goroutines

Go channels

Regular channels

Buffered channels

The select statement

The sync package

The simple mutex

The read-write mutex

Wait groups

Summary

Questions

Further reading

Section 2: The Frontend

Frontend with React.js

Prerequisites and technical requirements

The GoMusic project

Node.js and the npm

HTML, CSS, and Bootstrap

Project code

The React framework

How to construct React applications

Setting up the project

Installing React

Preparing the new project

JSX and React elements

React components

React application design

Props

State

Initializing the state object

Setting our state

Developer tools

Summary

Questions

Further reading

Building a Frontend for GoMusic

Prerequisites and technical requirements

Building GoMusic

Main pages

The navigational menu

The Products and Promotions pages

The About page

Modal dialog windows and handling credit cards

The Buy Item modal window outline

Credit card handling with React and Stripe

Creating a child React component to host Stripe elements

Making use of Stripe elements to handle credit card information

Submitting a credit card token to the backend

Creating a parent StripeProvider component

The Sign in and Register modal windows

Handling forms in the React framework

The Sign in page

The Registration form

User pages

The orders page

The user page navigational menu

Putting it all together – routes

Summary

Questions

Further reading

Section 3: Web APIs and Middleware in Go

RESTful Web APIs in Go with the Gin Framework

Technical requirements

RESTful APIs

Overview

The client-server architecture

URLs

HTTP methods

The Gin framework

Models and the database layer

Models

The database layer interface

Implementing RESTful APIs using the Gin framework

Defining routes

Creating handlers

Getting a full list of available products

Getting a list of promotions

Sign in new users or add new users

Sign out requests

Getting orders for a specific user

Charging a credit card

Putting it all together

Summary

Questions

Further reading

Advanced Web Go Applications with Gin and React

Technical requirements

The database layer

Relational databases

Setting up

The customer table

The orders table

The products table

ORM

GORM

Implementing the database layer

Middleware

Custom middleware

Security

Certificates and private keys

Establishing trust between the client and the server

Agreeing on, and using an encryption key

Supporting HTTPS in Gin

Password hashing

Implementing password hashing

Comparing the password

Credit card handling

Credit card handling at the backend

Revisiting the frontend code

The app structure

Interactions between the frontend and the backend

Using cookies

Deploying the frontend application

Summary

Questions

Further reading

Testing and Benchmarking Your Web API

Testing in Go

Mocking

Creating a mock db type

Unit testing in Go

Table-driven development

Benchmarking

Summary

Questions

Further reading

Introduction to Isomorphic Go with GopherJS

Technical requirements

GopherJS fundamentals

GopherJS types

Object types

Calling JavaScript functions from your Go code

GopherJS commands

Go bindings

Exporting code

Go Methods

Goroutines

GopherJS with React

The project

The project application's architecture

Building the React application in Go

Building a custom component

Summary

Questions

Further reading

Where to Go from Here?

Cloud-native applications

Microservices

Containers

Serverless applications

Continuous delivery

React Native

What is React Native?

React.js versus React Native

Similarities between React.js and React Native

Differences between React.js and React Native

Expo

Summary

Questions

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

The Go programming language has been rapidly adopted by developers for building web applications. With its impressive performance and ease of development, Go enjoys the support of a wide variety of open source frameworks for building scalable and high-performance web services and applications. This book is a comprehensive guide that covers all aspects of full stack development with Go. As you progress through the book, you'll gradually build an online musical instrument store application from scratch.

This clearly written, example-rich book begins with a practical exposure to Go development, by covering Go's building blocks, as well as Go's powerful concurrency features. We'll then explore the popular React framework, and work on building the frontend of our application with it. From there, you will build RESTful Web APIs utilizing the Gin framework, which is a very powerful and popular Go framework for Web APIs. After that, we will dive deeper into important software backend concepts, such as connecting to the database using an object-relational mapping (ORM), designing routes for your services, securing your services, and even charging credit cards using the popular Stripe API. We will also cover how to test and benchmark your applications efficiently in a production environment. In the concluding chapters, we will cover isomorphic development in pure Go by learning about GopherJS.

By the end of the book, you will be confident in taking on full stack web applications in Go.

Who this book is for

This book will appeal to developers who are planning to start building functional full stack web applications in Go. Basic knowledge of the Go language and JavaScript is expected. Some knowledge of HTML and CSS is also expected. The book targets web developers who are looking to move to the Go language.

What this book covers

Chapter 1, Welcome to Full Stack Go, provides an introduction to the topics covered in the book, as well as an overview of the architecture of the application that will be built throughout the book. This chapter also provides us with a glimpse of what to expect from the book.

Chapter 2, Building Blocks of the Go Language, introduces us to the building blocks of the Go language, and how to utilize them to build simple applications. It starts by covering Go's syntax for variables, conditional statements, loops, and functions. From there, it covers how to construct data structures in Go, and how to attach methods to them. It then concludes by focusing on learning how to write interfaces that can describe the behaviors of our program.

Chapter 3, Go Concurrency, covers the concurrency features of the Go language. It covers Go's concurrency primitives, such as goroutines, channels, and select statements, and then moves to cover some important concepts for productive concurrent software, such as locks, and wait groups.

Chapter 4, Frontend with React.js, covers the building blocks of the extremely popular React.js framework. It starts by taking a look at React components, which are the foundation for the React framework. From there, it covers props for passing data to components. And finally, it describes handling state and using developer tools. 

Chapter 5, Building a Frontend for GoMusic, builds our GoMusic frontend with the knowledge gained from the previous chapter. It builds the React components needed for the GoMusic store, and makes use of React's developer tools to troubleshoot the frontend. The majority of the frontend code will be covered in this chapter. 

Chapter 6, RESTful Web APIs in Go with the Gin Framework, introduces you to RESTful Web APIs and the Gin framework. It then goes ahead and dives into the key building blocks of Gin, and explains how to start writing Web APIs with it. It also covers how to do HTTP request routing and how to group HTTP request routes in Gin.

Chapter 7, Advanced Web Go Applications with Gin and React, discusses more advanced topics regarding the Gin web framework and our backend Web APIs. It covers important practical topics such as how to extend functionality by using middleware, how to achieve user authentication, how to attach logs, and how to add validations to our model bindings. It also covers the concept of ORMs, and how to connect our Web API backend to a MySQL database through a Go ORM. At the end, it will cover some of the remaining React code, then we will discuss how to connect the React app to our Go backend. The chapter also covers how to build and deploy a React application to production.

Chapter 8, Testing and Benchmarking Your Web API, discusses how to test and benchmark the Go application. It will help us to learn about the types and methods that can be used with the testing package to create unit tests that can be integrated with the code. It will then focus on learning how to benchmark our code to inspect its performance.

Chapter 9, Introduction to Isomorphic Go with GopherJS, covers GopherJS, which is a very popular open source project that helps to transpile Go's code into JavaScript, which in effect allows us to write frontend code in Go. If you are looking to write your frontend in Go instead of JavaScript, GopherJS is the way to do it. This chapter will discuss the basics of GopherJS, then cover some examples and use cases. We will also discuss how to combine GopherJS with React.js, by building a simple React application in GopherJS.

Chapter 10, Where to Go from Here? provides suggestions for where to continue the learning journey from here. It talks about cloud-native architectures, containers, and mobile app development using React Native.

To get the most out of this book

The best way to get the most benefit out of this book is to follow the chapters one by one. Try to practice the code examples along with the chapters. Most chapters contain a section that outlines the tools and software required for the code in the chapter to work. The code for each chapter will be available on GitHub.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

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/Hands-On-Full-Stack-Development-with-Go. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789130751_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles. Here is an example: "We'll also cover some concepts that are specific to Go, such as slice, panic, and defer."

A block of code is set as follows:

package mypackage

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

type Student struct{

Person

studentId int}func (s Student) GetStudentID()int{ return s.studentId}

Any command-line input or output is written as follows:

go install

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "This is called type inference, since you infer the variable type from the provided value."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: The Go Language

The objective of this section is to introduce the reader to the Go language. In this section of the book, the reader will gain practical knowledge of how to build effective software in Go.

This section consists of the following chapters:

Chapter 1

,

Welcome to Full Stack Go

Chapter 2

,

Building Blocks of the Go Language

Chapter 3

Go Concurrency

Welcome to Full Stack Go

This book is the result of an effort to provide you, the reader, with a very practical and concise learning tool for building full stack web applications in Go. Learning how to build full stack web applications in a powerful language such as Go can be a very valuable skill, as it allows you to write fully functional and scalable applications on your own. Go is known in the industry for both its performance and relative ease of use. This ensures that your applications can sustain growing data loads and expanding users, without suffering from scalability issues too early.

Full stack developers are the main drivers behind software startups; this is because of their ability to build products both quickly and efficiently from scratch. They are also typically the key members or the subject-matter experts (SMEs) in large corporations, as they help architect software systems, from the user interface down to the backend code. Even as an individual developer, learning full stack web programming can help you build your product ideas quickly, over a weekend or two.

In this chapter, we will cover the following topics:

What is full stack development?

What will we build?

The outline of this book

What is full stack development?

Before we take any further steps, we first need to answer a simple question; what does it really mean to be a full stack developer? A full stack developer can be defined as a software engineer who has the skill to work on both the frontend and the backend of an application. 

The frontend of a web application is basically anything related to the user interface of the application. For web applications, the technologies that are needed to build the user interface are HTML, CSS, and JavaScript. In production environments, an application can support different types of frontends, depending on the device by which the user is viewing the web application. For example, a frontend on a mobile smartphone may need different rules to accommodate the limited screen size of the device, compared to a screen size of a large desktop monitor. 

In order to make the application perform the tasks it is expected to do, the backend of a web application consists of all the software layers that need to communicate with the frontend of the application. The backend includes the database layers, the security layer, the user request-handling layer, all the API layers, and more. The backend of a web application can be written in any mature programming language. We will obviously be using Go as our backend language for this book.

What will we build?

Throughout this book, we will build a full stack web application from scratch. The application will be called GoMusic; it's a store for musical instruments written in React.js and Go. The following screenshot demonstrates how the main page will look:

Users will be able to browse the musical instruments in the store, buy what they like with their credit cards, and log in to their accounts to see their existing orders.

Let's take a look at the architecture of the application that we are going to build in this book.

The application architecture

Our application architecture will be relatively straightforward—we will use the extremely popular React.js framework for our frontend code, and then we will use the powerful Gin framework for our backend code. Gin comes with a wide array of useful packages that we will be using to build our web application. We will also make use of the Go object-relational mapping (GORM) package, which is one of the most popular object-relational mapping (ORM) layers in the Go language:

We'll build our application piece by piece, starting from the frontend, and then moving to the backend. We will cover some very important concepts in the world of modern web applications, such as reactive UIs, RESTful APIs, security, ORMs, credit card handling, testing, benchmarking, and more. 

As we cover these different topics, we'll cover the majority of the code involved in building the application. 

In the next section, we'll take a tour to discover the outline of this book, and what each chapter will cover.

The outline of this book

This book will cover numerous practical topics to help you acquire the deep skills necessary for a full stack developer:

In

Chapter 2

,

Go's Building Blocks,

and

Chapter 3

Go Concurrency,

we will take a deep and a practical tour into the Go language. You will learn about some of the key features of the language, as well as some of its popular design patterns.

In

Chapter 4

,

Frontend with React.js,

 and

Chapter 5

Building a Frontend for GoMusic,

we will cover how to build beautiful and responsive frontend applications using the React.js framework. This is also where we'll start building our GoMusic web application. We will cover React's building blocks, design patterns, best practices, and more. The majority of the frontend code of the book project will be covered in

Chapter 4

,

F

rontend with React.js,

 and 

Chapter 5

,

 

Building a Frontend for GoMusic

; however, we won't cover every single line of JavaScript code, so as not to lose focus. All the code will be available in the GitHub repository for this book.

In

Chapter 6

RESTful Web APIs in Go with the Gin Framework,

and 

Chapter 7

,

Advanced Web Go Applications with Gin and React,

we will start building our backend code using the Gin framework. We will cover RESTful APIs, ORMs, secure web connections, and more.

In

Chapter 8

,

Testing and Benchmarking Your Web API, 

we will learn how to test and benchmark our Go code using Go's testing package, and the best practices in the industry.

In

Chapter 9

,

Introduction to Isomorphic Go with GopherJS,

we will go through a crash course in isomorphic Go programming. Isomorphic Go programming is the practice of using Go for both the frontend and the backend. This is possible through the GopherJS framework.

Chapter 9

Introduction to Isomorphic Go with GopherJS,

is a standalone chapter, as it doesn't attempt to rebuild the GoMusic app using Isomorphic Go. However, the chapter covers how to build a React application in Isomorphic Go.

In

Chapter 10

,

Where to Go from Here? 

we will touch some topics that the reader should pursue in order to expand their knowledge beyond the scope of this book.

Let's get started with the learning journey!

Building Blocks of the Go Language

Welcome to the first chapter of our journey, where we will learn about full stack development in Go. This chapter is dedicated to readers who are not yet familiar with Go. If you are already proficient in the Go language, you can skip this chapter. We'll cover the basic building blocks that form the foundation of the Go language, which will be covered in a brief but practical manner. Then, we'll show you the Go syntax for basic programming constructs like functions and loops. We'll also cover some concepts that are specific to Go like slice, panic, and defer. This chapter assumes that you have some familiarity with programming concepts in general (like variables, functions, loops, and conditional statements). This chapter also assumes that you have some familiarity with Terminals, and command lines, as well as the concept of environmental variables.

A very good resource to learn about the Go language from scratch can be found at tour.golang.org.

In this chapter, we'll cover the following topics:

Basic concepts—packages, variables, data types, and pointers

Functions and closures

Conditional statements and loops

panic

,

recover

, and

defer

Go data structures

Go interfaces

Technical requirements

To follow along with this chapter, you can do either of the following:

Go to

play.golang.org

, which will allow you to run or test your code online

Download the Go programming language, along with a compatible IDE

If you haven't downloaded Go yet, you can download the Go language by going to https://golang.org/dl/, downloading the Go flavor for your operating system, and then installing it.

For the local IDE, I prefer Visual Studio Code (https://code.visualstudio.com), along with its popular Go plugin (https://code.visualstudio.com/docs/languages/go).

Go's playground

The Go playground is a fairly popular website, which allows the Go community to test Go code samples online. The website can be found at play.golang.org. Whenever you would like to quickly test a simple piece of Go code, visit the website and run your code.

Setting up Go's workspace

For you to write Go code on your computer, you need to set up a Go workspace. A Go workspace is a folder where you will write your Go code. Setting up a Go workspace is relatively simple. Here is what you will need to do:

First, make sure that you have Go installed. As we mentioned earlier, you can download and install Go by going to

https://golang.org/dl/

.

After installing Go, create a new folder in your computer for Go's workspace. Mine is called

GoProjects

.

Inside your Go workspace folder, you will have to create three main folders:

src

,

pkg

, and

bin

. It is very important to create folders with these exact names inside your Go workspace folder. Here is why these three folders are important:

The

src

folder will host all of your code files. Whenever you decide to start a new program, you will simply go to the

src

folder and create a new folder with your new program name.

The

pkg

folder typically hosts the compiled package files of your code.

The

bin

folder typically hosts the binary files that are produced by your Go programs.

You will need to set two environmental variables:

The first environmental variable is called

GoRoot

, and will include the path to your Go install.

GoRoot

should typically be taken care of by the Go installer. However, if it's missing, or you would like to move your Go installation to a different place, then you need to set

GoRoot

.

The second environmental variable is called

GoPath

.

GoPath

includes the path to your Go workspace folder. By default, if not set,

GoPath

is assumed to either to be at

$HOME/go

on Unix systems or

%USERPROFILE%\go

on Windows. There is an entire GitHub page which covers setting up

GoPath

in different operating systems, which can be found at

https://github.com/golang/go/wiki/SettingGOPATH

.

Once your Go environment is set up, you can use the Go tool, which is installed alongside the Go language so that you can compile and run your Go programs.

We'll take a look at some of the basic building blocks of the Go language in the next section.

Packages, variables, data types, and pointers

Packages, variables, data types, and pointers represent the most basic building blocks of the Go language. In this section, we'll cover them one by one from a practical point of view.

Packages

Any Go program consists of one or more packages. Each package is basically a folder, which contains one or more Go files. Every single Go code file you write must belong to a package. Package folders are found inside the src folder of your Go workspace.

When you write Go code, you declare your package name at the very top of your Go file. Here is what this looks like in code:

package mypackage

Here, mypackage is the name of the package that my Go file belongs to. It's idiomatic in Go to have your package name in lower case letters. It is usually preferable to name your package folder the same as your package name. So, when you create a new package, simply create a new folder with your package name, and then create your package files inside that folder.

To import an external package and use it in your own package, you need to use the import keyword. For example, a popular package in Go's standard library is the fmt package, which allows you to write data to the standard output (that is, write to your console screen). Let's assume we want to use the fmt package from within our package. Here is what the code would look like:

package mypackage import "fmt"

Some package folders can exist inside folders of other packages. For example, the folder that contains the rand package in Go, which is used to generate random numbers, exists inside the folder that contains the math package in Go. To import a package like that, you need to use the following syntax:

import "math/rand"

Now, what if we would like to import multiple packages at once? It's easy—the syntax will end up looking like this:

import ( "fmt" "math/rand" )

Go does not allow you to import a package and then not use it to ensure that your code is clean and concise. However, there are some cases (which we'll cover later in this book) where you will want to load a package, but not use it directly. This can be accomplished by appending an underscore before the package name in the import statement. Here is what this would look like:

import ( "database/sql" _ "github.com/go-sql-driver/mysql")

The most famous package name is main. Your main package is the first package that runs in your Go program.

To compile a Go program, you will need to navigate to the folder where your main package lives in the console, and then type the following command:

go install

This command will compile your Go program and then place the resulting binary in the bin folder of your workspace.

Alternatively, you can run the following command:

go build

This command will compile and then deploy the resulting binary in the current folder.

If you would like to specify an output path and a filename, you can run the following command:

go build -o ./output/myexecutable.exe

This will compile your code and then package it in an executable called myexecutable.exe at the specified output folder. If your operating system is not Windows, you can ignore the exe extension in the preceding example.

Pointers

The concept of pointers is simple—a pointer