(This page has no text content)
GoLang Go, also known as GoLang, is a Google-developed open-source, compiled, and statically typed computer language. Go is a general purpose programming lan- guage with a straightforward syntax and a large standard library. The building of highly accessible and scalable web apps is one of the primary areas where GoLang is widely used. It may also be used to develop command-line programs, desktop applications, and even mobile apps. Go was designed from the ground up for networking and infrastructure-related applications. It was developed as a replacement for popular server-side languages like Java and C++. The Go programming language aims to combine the efficiency and safety of a statically typed, compiled language with the simplicity of program- ming of an interpreted, dynamically typed language. It also aspires to be cutting- edge, with networked and multicore computer capabilities. Why Should You Learn GoLang? GoLang is becoming one of the most popular languages, which means that learning it can open up new doors of opportunity and even help you land a job at various companies that use Go extensively. Ease of writing concurrent programs, fast compilation, simple syntax, and static linking are some of the features that make Go an ideal candidate for developing various applications. Features: • Step-by-step approach to problem solving and skill development • A quick run-through of the basic concepts, in the form of a “Crash Course”
• Advanced, hands-on core concepts, with a focus on real-world problems • Industry-level coding paradigm, practice-oriented explanatory approach • Special emphasis on writing clean and optimized code, with addi- tional chapters focused on coding methodology
GoLang The Ultimate Guide Edited by Sufyan bin Uzayr
First edition published 2023 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2023 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf. co.uk Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. Library of Congress Cataloging-in-Publication Data Names: Bin Uzayr, Sufyan, author. Title: GoLang : the ultimate guide / Sufyan bin Uzayr. Description: First edition. | Boca Raton : CRC Press, 2023. | Includes bibliographical references and index. Identifiers: LCCN 2022025681 (print) | LCCN 2022025682 (ebook) | ISBN 9781032312323 (hardback) | ISBN 9781032312316 (paperback) | ISBN 9781003309055 (ebook) Subjects: LCSH: Go (Computer program language) Classification: LCC QA76.73.G63 B56 2023 (print) | LCC QA76.73.G63 (ebook) | DDC 005.13/3--dc23/eng/20220919 LC record available at https://lccn.loc.gov/2022025681 LC ebook record available at https://lccn.loc.gov/2022025682 ISBN: 9781032312323 (hbk) ISBN: 9781032312316 (pbk) ISBN: 9781003309055 (ebk) DOI: 10.1201/9781003309055 Typeset in Minion by KnowledgeWorks Global Ltd.
v Contents Acknowledgments, xix About the Author, xxi Chapter 1 ◾ Crash Course in GoLang 1 IS IT REFERRED TO AS Go OR GoLang? 2 WHAT IS THE PURPOSE OF GoLang? 2 WHY IS Go SO POPULAR? 2 Other Programming Languages vs. Go 3 Python vs. Go 3 But How Does Go Stack Up against Python? 3 SHOULD WE STUDY Go? 4 Go PROGRAMMING FEATURES 4 WHAT MAKES GoLang SUPERIOR TO OTHER COMPUTER LANGUAGES? 5 GoLang’s Core Capability 5 Multithreading and Concurrency 6 From within, Go Empowers Hardware 6 Unmatched Simplicity of Go 7 Built-in Testing and Profiling Framework 7 Easy Learning Curve 7 BEGINNING WITH Go 8 Text Editor 8 Finding a Go Compiler 8
vi ◾ Contents INSTALL Go ON WINDOWS 8 How Can We Know Which Go Language Version Is Preinstalled? 9 Downloading and Installing Go 9 WRITING THE FIRST Go PROGRAM 10 Why Is There a “Go Language”? 11 What Is Missing in Go That the Other Languages Have? 11 Hardware Restrictions 12 The Upsides and Downsides of the Go Language 12 TERMINAL 13 The Open Terminal Tool Window 13 Start the New Session 14 INSTALL Go ON Mac 14 Making Our First Program 16 Implement a Go Program 16 Do Go Programs Interact with Programs Written in C/C++? 17 HOW CAN WE CREATE AN EMPTY FILE IN GoLang? 17 HOW TO MAKE A DIRECTORY IN Go 19 HOW TO READ AND WRITE A Go PROGRAM 20 HOW DO WE RENAME AND TRANSFER A FILE IN GoLang? 23 HOW TO READ A FILE LINE BY LINE AND CONVERT IT TO A STRING 24 BASIC SYNTAX 25 Tokens 25 Line Separator 25 Comments 25 Identifiers 26 Keywords 26 Whitespace 27 DATA TYPES IN Go 27 Numbers 28
Contents ◾ vii Booleans 30 Strings 30 VARIABLES IN Go 31 Declaring a Variable 32 Employing the var Keyword 32 Using the Short Variable Declaration 35 CONSTANTS 38 How Should We Declare? 39 Untyped and Typed Numeric Constants 39 Numeric Constant 39 String Literals 41 Boolean Constant 42 VARIABLE SCOPE IN Go 43 Local Variables 43 Global Variables 44 DECLARATION OF MULTIPLE VARIABLES 46 SHORTHAND DECLARATION 48 OPERATORS IN Go 49 Arithmetic Operators 50 Relational Operators 51 Logical Operators 53 Bitwise Operators 53 Assignment Operators 54 Misc Operators 56 CONTROL STATEMENTS 57 if Statement 57 if…else Statement 58 Nested if Statement 60 if..else..if Ladder 61 SWITCH STATEMENT 63 Expression Switch 63 Type Switch 64
viii ◾ Contents ARRAYS 65 Creating and Using an Array 65 Using var Keyword 65 Using a Shorthand Declaration 66 Multidimensional Array 67 How Do You Copy an Array into Another Array? 68 How Can We Pass an Array to a Function? 69 SLICES 70 Slice Declaration 70 Slice Components 71 How Do We Create and Begin a Slice? 72 Using Slice Literal 72 Using an Array 72 Using an Existing Slice 73 Using the make() Function 74 How to Iterate over a Slice 75 Using the for Loop 75 Using Range in a for Loop 76 Using a Blank Identifier in a for Loop 76 Slice Composite Literal 77 How to Sort a Slice of ints 77 Ints 78 IntsAreSorted 78 How Do We Trim a Slice of Bytes in GoLang? 79 How Do We Split a Slice of Bytes? 81 STRING 82 String Literals 83 Using Double Quotes (“”) 83 Using Backticks(“) 83 How Do We Trim a String? 84 Trim 84 TrimLeft 85
Contents ◾ ix TrimRight 86 TrimSpace 87 TrimSuffix 88 TrimPrefix 89 How to Split a String 90 Split 90 SplitAfter 91 SplitAfterN 92 MAPS 93 How Do We Create and Initialize Maps? 94 Simple 94 Using the make() Function 95 WHAT IS A BLANK IDENTIFIER (underscore)? 96 DEFER KEYWORD 97 PANIC IN GoLang 98 RECOVER 99 CLOSURES 100 RECURSION 101 POINTERS 102 What Are Points Used For? 102 Pointers Declaration and Initialization 103 Declaring a Pointer 103 Pointer Initialization 103 Dereferencing a Pointer 104 In GoLang, How Can We Instantiate a Struct Using the New Keyword? 105 Pointers to a Function 106 Create a Pointer and Pass It to the Function 106 Passing an Address of the Variable to Function Call 107 Pointer to a Struct 108 Pointer to Pointer in Go 109 How to Declare a Pointer to a Pointer 109
x ◾ Contents Comparing Pointers 110 == operator 110 != operator 111 GoLang STRUCTURES 112 Pointers to a Struct 114 GoLang’s NESTED STRUCTURE 114 GoLang METHODS 115 Method with the Struct Type Receiver 116 Method with the Non-Struct Type Receiver 116 Methods with the Pointer Receiver 117 INTERFACES 118 How Do We Make an Interface? 119 How to Implement Interfaces 119 Why Are Go Interfaces Wonderful? 120 Redundant Functions 120 INHERITANCE 121 POLYMORPHISM USING INTERFACES 123 Chapter 2 ◾ Test-Driven Development 125 DEVELOPING A NEW PROJECT 126 MAKING Go FILES 126 RUN TESTS 127 A TEST THAT FAILED 127 THE FUNCTION BEING TESTED 129 WRITING A TEST-FIRST FUNCTION 129 REFACTORING Go WITH Go/ANALYSIS 131 Invoke the Refactoring Command 131 Conflicts Resolve 131 Configure the Refactoring Options 131 My Top Four Go Refactoring Approaches 132 Method of Extraction 132 Method of Move 133
Contents ◾ xi Create a Parameter Object 135 Replace Symbolic Constant with Magic Number 136 REFACTORING OUR FIRST Go CODE 137 Include a Parameter Check 138 Add String Formatting 138 Take Out the Code 139 Write a Test 139 GoLang ERROR HANDLING 140 Errors in GoLang 140 Creating Our Own Mistakes 141 Errors Caused by Strings 141 Data Custom Mistakes 142 Handling Errors in Functions 143 Defer 144 Panic 146 Recover 149 Error Wrapping 150 Casting Errors 152 WRITE UNIT TESTING IN Go 153 Beginning 153 Unique to Go 154 Setup and Teardown 155 Testing within the Same Package 156 Five Basic Techniques and Strategies for Developing GoLang Unit Tests 157 Chapter 3 ◾ Packaging in GoLang 163 PACKAGES IN GoLang 163 Workspace 163 Main Package 164 Import Packages 165 Install Third-Party Packages 165
xii ◾ Contents Init Function 166 Important Considerations 167 Giving the Packages Names 169 Code Exported 170 Essential Go Packages and Libraries 172 Awesome Go 172 GoLang-Set 172 Color 174 Now 175 Gen 176 Gorm 178 Goose 180 Glide 180 Ginkgo 181 Etcd 181 NSQ 182 Docker 184 Kubernetes 184 DEPENDENCY MANAGEMENT 184 Versioning 184 Modules 185 Installing Dependencies 186 Dependencies Must Authenticate 187 Remove Unused Dependencies 187 Installing Dependencies That Are Missing 188 Updating the Versions of Dependencies 188 Listing Dependencies 190 Module vs. Package 190 Naming 190 Fetching Packages 191
Contents ◾ xiii Chapter 4 ◾ Handling Concurrency 193 CONCURRENCY 193 Illustration of the Sleeping Barber Issue 195 Example of a Producer-Consumer Problem 198 Goroutines – CONCURRENCY IN GoLang 201 Go Concurrent Programming 201 Issues with Multithreading 201 How to Create a Goroutine 202 MULTIPLE Goroutines 202 What Is the Difference between Parallelism and Concurrency? 204 Goroutines Provide Several Advantages over Threads 204 COMMUNICATE TO SHARE MEMORY 204 HOW TO USE Goroutines TO ACCESS SHARED RESOURCES 207 Access Shared Resources Using Goroutines 207 Using Mutual Exclusion to Get Access to Shared Resources 207 Using Atomic Counters to Get Access to Shared Resources 209 Concurrency Issues 210 Concurrency Disadvantages 211 Benefits of Concurrency 211 Problems with Concurrency 211 Chapter 5 ◾ GoLang for JavaScript Developers 213 FLOW CONTROL 213 Loop Control Statements in Go 219 Break Statement 220 Goto Statement 220 Continue Statement 221 TYPES 222 Basic Types 222 Numbers 222
xiv ◾ Contents Booleans 224 Strings 225 Type Conversion 226 Type Assertion 226 Structs 228 Initializing 230 Composition vs. Inheritance 230 HOW DO YOU MAKE MODULES IN GoLang? 235 Adding Dependencies to the Go Module 237 PACKAGE MANAGEMENT USING Go MODULES 237 What Exactly Is the Go Module? 238 Starting Out 239 Module Initializing 239 Setting Up Dependencies 239 Eliminating Unnecessary Dependencies 239 Updating a Dependency Version 240 ERROR HANDLING 240 Error Type Representation 241 Various Approaches to Getting More Information from an Error 242 Don’t Ignore Errors 246 IN GoLang, THERE ARE SEVERAL TECHNIQUES TO COMPARE STRINGS 247 Making Use of Comparison Operators 247 Using the Compare() Method 249 FUNCTIONS IN Go 250 Function Declaration 250 Function Calling 251 Function Arguments 252 FUNCTION RETURNING MULTIPLE VALUES 253 Giving Names to the Return Values 254 VARIADIC FUNCTIONS 255
Contents ◾ xv ANONYMOUS FUNCTION 256 GoLang main AND init FUNCTIONS 256 main() Function 257 init() Function 257 Chapter 6 ◾ Code Optimization 259 A PATTERN FOR OPTIMIZING Go 259 Why Is Code Optimization Necessary? 267 Code Base That Is Cleaner 268 Improved Consistency 268 Pages That Load Faster 268 Improved Code Readability 269 More Efficient Refactoring 269 Easier to Understand Debugging 269 Enhanced Workflow 269 Code Upkeep Is Now Easier 270 Improved Feature Development 270 The Ultimate Guide to GoLang Performance Optimization 270 GoLang Performance Hints That Have Been Proven and Tested 270 Optimization of Resource Efficiency 270 Optimization of Latency in GoLang 271 Efficiency of Algorithms 271 Patterns of GoLang Application Performance 271 Use Goroutines Sparingly 271 CPU Work Should Parallelize 272 Asynchronous I/O Operations 272 Keep an Eye on Our Timeouts 272 Memory Should Not Allocate in Hot Spots 272 Make Use of Lock-Free Algorithms 272 Prefer Read-Only Locks 272 Reduce or Eliminate the Use of ‘cgo’ 272 Make Use of Buffered I/O 273
xvi ◾ Contents Use Binary Instead 273 StringBuffer and StringBuilder Are Preferable 273 Make Use of Regular Expressions 273 Slices Should Preallocate 273 Select Protocol Buffers and MessagePack as Our Options 273 For Maps, Use int Rather Than a String 273 GoLang FOR SECURE CODING 273 Stuck in a Rut with Manual Security 273 With Go, There Is a Need for Integrated, Automated Security 274 How Does Instrument-Based Security Work in the Go Pipeline? 275 Contrast Goes Above and Beyond with Modern Application Security 276 Go Security Best Practices 276 Verify the Input Entries 277 Make Use of HTML Templates 278 Protect Ourselves against SQL Injections 278 Encrypt Any Sensitive Data 279 Make HTTPS Communication Mandatory 280 Be Cautious of Mistakes and Logs 282 BEST PRACTICES FOR GoLang 283 Syntax 284 Assign Datatypes to Newly Created Variables 284 Do Not Declare a Variable or Import a Package That We Do Not Require 284 Follow Proper Naming Conventions 284 Make Use of Comments to Help in Knowledge Transfer 285 Simple, Readable, and Maintainable Code 285 Avoid Nesting by Dealing with Mistakes First 285 Avoid Utility Repeats 285 To Address Exceptional Circumstances, Use the Type Switch 285 Go Code Organization 286
Contents ◾ xvii For Use in CI/CD Workflows 286 Make Use of Go Modules 286 Ensure Immutability and Availability Using GOPROXY 287 Chapter 7 ◾ GoLang Tutorials and Projects 289 WEB APPLICATION TO GENERATE QR CODE IN GoLang 289 Install the Necessary Package 290 Development 290 Main.go Source Code 290 Generator.html Source Code 291 Implementation 291 SETTING UP THE Go HTTP CLIENT 291 HTTP Client in GoLang 292 POST and GET Requests 293 Adding Request Headers 294 Our Requests Are Being Authorized 296 WHAT IS THE GoLang REST API? 297 Using GoLang to Consume a REST API 299 Project Setup 299 Imports 299 Example of a Response 300 Struct 300 Code 300 Run the Project 301 APPRAISAL, 303 CHEAT SHEET, 319 BIBLIOGRAPHY, 329 INDEX, 333
(This page has no text content)
xix Acknowledgments There are many people who deserve to be on this page, for this book would not have come into existence without their support. That said, some names deserve a special mention, and I am genuinely grateful to: • My parents, for everything they have done for me. • My siblings, for helping with things back home. • The Parakozm team, especially Divya Sachdeva, Jaskiran Kaur, and Vartika, for offering great amounts of help and assistance during the book-writing process. • The CRC team, especially Sean Connelly and Danielle Zarfati, for ensuring that the book’s content, layout, formatting, and everything else remain perfect throughout. • Reviewers of this book, for going through the manuscript and pro- viding their insight and feedback. • Typesetters, cover designers, printers, and all other helpers in the development of this book. • All the folks associated with Zeba Academy, either directly or indi- rectly, for their help and support. • The programming community in general, and the web development community in particular, for all their hard work and efforts. Sufyan bin Uzayr
Comments 0
Loading comments...
Reply to Comment
Edit Comment