Go Programming – From Beginner to Professional, 2nd Edition: Learn everything you need to build modern software using Go / Программирование на Go - от новичка до профессионала, 2-е издание: Узнайте все, что вам нужно для создания современного программного обеспечения с помощью Go
Год издания: 2024
Автор: Coyle Samantha / Койл Саманта
Издательство: Packt Publishing
ISBN: 978-1-80324-305-4
Язык: Английский
Формат: PDF/EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 680
Описание: Harness the power of Go through hands-on coding examples, covering basic to advanced topics like modules, database interfacing, RESTful APIs, concurrency, and beyond.
Key Features
Leverage Go's standard library through practical examples and simplify development tasks using best practices
Master effective idiomatic Go syntax, including variables, functions, and loops, to handle data
Build fully functional web applications with capabilities such as database connectivity and RESTful API creation
Book Description
Go Programming – From Beginner to Professional is a comprehensive guide that takes your proficiency in the Go programming language from novice to expert. Starting with fundamental concepts, this book covers variables, command-line tools, and working with data before delving into advanced concepts, including error handling, interfaces, and generics, harnessing Go’s latest features through hands-on exercises. Along the way, you’ll learn to structure projects using Go modules, manage packages effectively, and master debugging techniques.
As you progress, you’ll get to grips with practical application-centric aspects such as command-line programming, file manipulation, and working with SQL databases. Additionally, the book explores web server development, RESTful APIs, and utilizing the Go HTTP client to interact with web applications. Further enhancing your Go skills, you’ll learn concurrent programming, testing methodologies, Go tools, and how to deploy applications in the cloud. Throughout the book, you’ll uncover Go’s hidden gems and gain insights into time manipulation, best practices, and more.
By the end of this book, you’ll have worked through practical exercises and activities that’ll equip you with the knowledge and skills needed to excel as a proficient Go developer, primed for success in real-world projects.
What you will learn
Understand the Go syntax and apply it proficiently to handle data and write functions
Debug your Go code to troubleshoot development problems
Safely handle errors and recover from panics
Implement polymorphism using interfaces and gain insight into generics
Work with files and connect to popular external databases
Create an HTTP client and server and work with a RESTful web API
Use concurrency to design efficient software
Use Go tools to simplify development and improve your code
Who this book is for
Designed for both complete beginners in Go as well as professionals transitioning from another programming language, this book equips developers with skills needed to build real-world projects and launch their career in Go. With a step-by-step approach, beginners can grasp Go fundamentals even without prior programming experience, and gradually advance to idiomatic Go best practices, exploring the latest features of the language.
Воспользуйтесь возможностями практических примеров программирования, охватывающих как базовые, так и продвинутые темы, такие как модули, взаимодействие с базами данных, RESTful API, параллелизм и многое другое
Kлючевые функции
Используйте стандартную библиотеку Go с помощью практических примеров и упрощайте задачи разработки, используя лучшие практики
Освоите эффективный идиоматический синтаксис Go, включая переменные, функции и циклы, для обработки данных
Создавайте полнофункциональные веб-приложения с такими возможностями, как подключение к базе данных и создание RESTful API
Описание книги
Go Programming – От новичка до профессионала - это всеобъемлющее руководство, которое повысит ваш уровень владения языком программирования Go от новичка до эксперта. Начиная с фундаментальных концепций, в этой книге рассматриваются переменные, инструменты командной строки и работа с данными, а затем переходят к более продвинутым концепциям, включая обработку ошибок, интерфейсы и обобщения, а также использование новейших возможностей Go с помощью практических упражнений. Попутно вы научитесь структурировать проекты с помощью модулей Go, эффективно управлять пакетами и освоите методы отладки.
По мере продвижения вы познакомитесь с практическими аспектами, ориентированными на приложения, такими как программирование в командной строке, манипулирование файлами и работа с базами данных SQL. Кроме того, в книге рассматривается разработка веб-серверов, RESTful API и использование HTTP-клиента Go для взаимодействия с веб-приложениями. Совершенствуя свои навыки работы с Go, вы познакомитесь с параллельным программированием, методологиями тестирования, инструментами Go и с тем, как развертывать приложения в облаке. На протяжении всей книги вы будете раскрывать скрытые преимущества Go и получать представление о манипулировании временем, лучших практиках и многом другом.
К концу прочтения этой книги вы освоите практические упражнения, которые помогут вам приобрести знания и навыки, необходимые для того, чтобы преуспеть в качестве опытного разработчика Go и добиться успеха в реальных проектах.
Чему вы научитесь
Разберитесь в синтаксисе Go и умело применяйте его для обработки данных и написания функций
Отладьте свой код Go для устранения неполадок при разработке
Безопасно обрабатывайте ошибки и восстанавливайтесь после сбоев
Реализуйте полиморфизм с помощью интерфейсов и получите представление о типовых параметрах
Работайте с файлами и подключайтесь к популярным внешним базам данных
Создайте HTTP-клиент и сервер и работайте с RESTful web API
Используйте параллелизм для разработки эффективного программного обеспечения
Используйте инструменты Go для упрощения разработки и улучшения кода
Для кого предназначена эта книга
Предназначенная как для начинающих пользователей Go, так и для профессионалов, осваивающих другие языки программирования, эта книга дает разработчикам навыки, необходимые для создания реальных проектов и начала их карьеры в Go. Благодаря пошаговому подходу новички могут освоить основы Go, даже не имея предварительного опыта программирования, и постепенно переходить к лучшим методам идиоматического программирования Go, изучая новейшие возможности языка.
Примеры страниц (скриншоты)
Оглавление
Preface xxi
Part 1: Scripts
1
Variables and Operators 3
Technical requirements 3
Introduction to Go 3
What does Go look like? 4
Exercise 1.01 – using variables, packages, and
functions to print stars 10
Activity 1.01 – defining and printing 11
Declaring variables 12
Declaring a variable using var 12
Exercise 1.02 – declaring a variable using var 13
Declaring multiple variables at once with var 14
Exercise 1.03 – declaring multiple variables at
once with var 14
Skipping the type or value when declaring
variables 15
Exercise 1.04 – skipping the type or value
when declaring variables 15
Type inference gone wrong 17
Short variable declaration 17
Exercise 1.05 – implementing a short variable
declaration 17
Declaring multiple variables with a short
variable declaration 19
Exercise 1.06 – declaring multiple variables
from a function 20
Using var to declare multiple variables in one
line 21
Non-English variable names 22
Changing the value of a variable 23
Exercise 1.07 – changing the value of a variable 23
Changing multiple values at once 24
Exercise 1.08 – changing multiple values at once 24
Operators 25
Exercise 1.09 – using operators with numbers 26
Shorthand operators 29
Exercise 1.10 – implementing shorthand
operators 29
Comparing values 30
Exercise 1.11 – comparing values 31
Zero values 33
Exercise 1.12 – zero values 33
Value versus pointer 35
Getting a pointer 37
Exercise 1.13 – getting a pointer 37
Getting a value from a pointer 38
Exercise 1.14 – getting a value from a pointer 39
Function design with pointers 40
Exercise 1.15 – function design with pointers 41
Activity 1.02 – pointer value swap 43
Constants 43
Exercise 1.16 – constants 44
Enums 47
Activity 1.03 – message bug 50
Activity 1.04 – bad count bug 51
Summary 51
2
Command and Control 53
Technical requirements 53
Introduction 53
if statements 54
Exercise 2.01 – a simple if statement 54
if else statements 56
Exercise 2.02 – using an if else statement 56
else if statements 57
Exercise 2.03 – using an else if statement 57
initial if statements 58
Exercise 2.04 – implementing initial if
statements 59
Expression switch statements 61
Exercise 2.05 – using a switch statement 62
Exercise 2.06 – switch statements and
multiple case values 63
Exercise 2.07 – expressionless switch statements 65
Loops 66
Exercise 2.08 – using a for i loop 67
Exercise 2.09 – looping over arrays and slices 68
range loop 69
Exercise 2.10 – looping over a map 70
Activity 2.01 – looping over map data using
range 71
Activity 2.02 – implementing FizzBuzz 72
break and continue 74
Exercise 2.11 – using break and continue to
control loops 74
Activity 2.03 – bubble sort 76
goto statements 77
Exercise 2.12 – using goto statements 77
Summary 79
3
Core Types 81
Technical requirements 81
Introduction 81
True and false 82
Exercise 3.01 – Program to measure password
complexity 83
Numbers 86
Integers 86
Floating-point numbers 88
Exercise 3.02 – Floating-point number accuracy 89
Overflow and wraparound 91
Exercise 3.03 – Triggering number wraparound 91
Big numbers 93
Exercise 3.04 – Big numbers 93
byte 94
Text 95
Rune 96
Exercise 3.05 – Safely looping over a string 99
The nil value 101
Activity 3.01 – Sales tax calculator 101
Activity 3.02 – Loan calculator 102
Summary 103
4
Complex Types 105
Technical requirements 105
Introduction 105
Collection types 106
Arrays 106
Exercise 4.01 – Defining an array 107
Comparing arrays 107
Exercise 4.02 – Comparing arrays 108
Initializing arrays using keys 109
Exercise 4.03 – Initializing an array using keys 110
Reading from an array 111
Exercise 4.04 – Reading a single item from an
array 111
Writing to an array 112
Exercise 4.05 – Writing to an array 113
Looping over an array 114
Exercise 4.06 – Looping over an array using a
“for i” loop 114
Modifying the contents of an array in a loop 116
Exercise 4.07 – Modifying the contents of an
array in a loop 116
Activity 4.01 – Filling an array 117
Slices 118
Exercise 4.08 – Working with slices 118
Appending multiple items to a slice 120
Exercise 4.09 – Appending multiple items to a
slice 120
Creating slices from slices and arrays 122
Exercise 4.10 – Creating slices from a slice 122
Understanding slice internals 123
Exercise 4.11 – Using make to control the
capacity of a slice 124
Background behavior of slices 126
Exercise 4.12 – Controlling internal slice
behavior 126
Map fundamentals 130
Exercise 4.13 – Creating, reading, and writing
a map 132
Reading from maps 133
Exercise 4.14 – Reading from a map 133
Activity 4.02 – Printing a user’s name based
on user input 135
Activity 4.03 – Slicing the week 136
Deleting elements from a map 137
Exercise 4.15 – Deleting an element from a map 137
Activity 4.04 – Removing an element from a
slice 138
Simple custom types 139
Exercise 4.16 – Creating a simple custom type 139
Structs 140
Exercise 4.17 – Creating struct types and values 141
Comparing structs to each other 144
Exercise 4.18 – Comparing structs to each other 144
Struct composition using embedding 146
Exercise 4.19 – Struct embedding and
initialization 147
Activity 4.05 – Creating a locale checker 149
Type conversions 150
Exercise 4.20 – Numeric type conversions 151
Type assertions and interface{} 152
Exercise 4.21 – Type assertions 153
Type switch 155
Exercise 4.22 – Type switch 155
Activity 4.06 – Type checker 158
Summary 159
Part 2: Components 161
5
Functions – Reduce, Reuse, and Recycle 163
Technical requirements 163
Introduction 163
Functions 164
Parts of a function 165
The checkNumbers function 167
Exercise 5.01 – creating a function to print
salesperson expectation ratings from the
number of items sold 170
Parameters 171
The difference between an argument and a
parameter 173
Exercise 5.02 – mapping index values to
column headers 174
Function variable scope 176
Return values 178
Exercise 5.03 – creating a checkNumbers
function with return values 178
Activity 5.01 – calculating the working hours
of employees 179
Naked returns 181
Exercise 5.04 – mapping a CSV index to a
column header with return values 183
Variadic functions 185
Exercise 5.05 – summing numbers 188
Anonymous functions 189
Exercise 5.06 – creating an anonymous
function to calculate the square root of a
number 191
Closures 192
Exercise 5.07 – creating a closure function to
decrement a counter 193
Function types 195
Exercise 5.08 – creating various functions to
calculate salary 199
defer 200
Activity 5.02 – calculating the payable
amount for employees based on working hours 204
Separating similar code 205
Summary 207
6
Don’t Panic! Handle Your Errors 209
Technical requirements 209
Introduction 209
What are errors? 210
Syntax errors 211
Runtime errors 212
Exercise 6.01 – runtime errors while adding
numbers 212
Semantic errors 214
Exercise 6.02 – a semantic error with walking
distance 215
Error handling using other programming
languages 216
Error interface type 217
Creating error values 220
Exercise 6.03 – creating an application to
calculate pay for the week 221
Panic 225
Exercise 6.04 – Crashing the program on
errors using a panic 229
Recover 231
Exercise 6.05 – recovering from a panic 234
Guidelines when working with errors and
panics 237
Error wrapping 238
Activity 6.01 – creating a custom error
message for a banking application 239
Activity 6.02 – validating a bank customer’s
direct deposit submission 239
Activity 6.03 – panic on invalid data
submission 240
Activity 6.04 – preventing a panic from
crashing the app 241
Summary 242
7
Interfaces 243
Technical requirements 243
Introduction 243
Interface 244
Defining an interface 246
Implementing an interface 248
Advantages of implementing interfaces
implicitly 249
Exercise 7.01 – implementing an interface 251
Duck typing 253
Polymorphism 254
Empty interface 266
Type assertion and switches 268
Exercise 7.03 – analyzing empty interface{} data 273
Activity 7.01 – calculating pay and
performance review 277
any 278
Summary 278
8
Generic Algorithm Superpowers 281
Technical requirements 281
Introduction 282
When to use generics? 282
Type parameters 284
Activity 8.01 – a minimum value 285
Type constraints 286
Exercise 8.01 – calculate the maximum value
using interfaces 287
Exercise 8.02 – calculate the largest stock of
items on a ranch 289
Type inference 291
When to use generics versus interfaces 292
What are some best practices? 292
Summary 293
Part 3: Modules
9
Using Go Modules to Define a Project 297
Technical requirements 297
Introduction 297
What is a module? 298
Key components when working
with Go modules 298
The go.mod file 299
The go.sum file 299
How are modules helpful? 300
Precise and simplified dependency
management 300
Versioning and reproducibility 300
Improved collaboration 301
Dependency safety 301
Ease of use while promoting isolation
and modularity 301
Exercise 09.01 – creating and using
your first module 301
When should you use external
modules, and why? 304
Exercise 09.02 – using an external
module within our module 304
Consuming multiple modules within
a project 306
Activity 9.01 – consuming multiple modules 306
Defining multiple modules within a
project 307
Go workspaces 308
Exercise 09.03 – working with workspaces 308
Summary 311
10
Packages Keep Projects Manageable 313
Technical requirements 313
Introduction 314
Maintainable 316
Reusable 316
Modular 317
What is a package? 317
Package structure 318
Package naming 319
Package declarations 321
Exported and unexported code 323
Package alias 326
Main package 326
Exercise 10.01 – Creating a package to
calculate areas of various shapes 327
The init() function 331
Exercise 10.02 – Loading budget categories 334
Executing multiple init() functions 335
Exercise 10.03 – Assigning payees to budget
categories 337
Activity 10.01 – Creating a function to
calculate payroll and performance review 338
Summary 339
11
Bug-Busting Debugging Skills 341
Technical requirements 341
Introduction 341
Methods for bug-free code 343
Coding incrementally and testing often 343
Writing unit tests 343
Handling all errors 343
Performing logging 344
Formatting using fmt 344
Exercise 11.01 – Working with fmt.Println 344
Formatting using fmt.Printf() 345
Additional options for formatting 349
Exercise 11.02 – Printing decimal, binary, and
hex values 352
Basic debugging 353
Printing Go variable types 357
Exercise 11.03 – Printing the Go
representation of a variable 358
Logging 360
Logging fatal errors 363
Activity 11.01 – Building a program to
validate Social Security Numbers 364
Debugging in live or restricted
environments 366
Summary 367
12
About Time 369
Technical requirements 369
Introduction 369
Making time 370
Exercise 12.01 – Creating a function to return
a timestamp 372
Comparing time 373
Duration calculation 375
Managing time 378
Exercise 12.02 – Duration of execution 379
Formatting time 380
Exercise 12.03 – What is the time in your zone? 383
Activity 12.01 – Formatting a date according
to user requirements 384
Activity 12.02 – Enforcing a specific format of
date and time 385
Activity 12.03 – Measuring elapsed time 386
Activity 12.04 – Calculating the future date
and time 387
Activity 12.05 – Printing the local time in
different time zones 387
Summary 388
Part 4: Applications
13
Programming from the Command Line 391
Technical requirements 391
Introduction 391
Reading arguments 392
Exercise 13.01 – saying hello using a name
passed as an argument 392
Using flags to control behavior 393
Exercise 13.02 – using flags to say hello
conditionally 394
Streaming large amounts of data in
and out of your application 395
Exercise 13.03 – using pipes, stdin, and stdout
to apply a Rot13 encoding to a file 396
Exit codes and command line best
practices 399
Knowing when to stop by watching
for interrupts 400
Starting other commands from your
application 401
Exercise 13.04 – creating a stopwatch with a
time limit 402
Terminal UIs 403
Exercise 13.05 – creating a wrapper for our
Rot13 pipeline 403
go install 407
Summary 408
14
File and Systems 411
Technical requirements 411
Introduction 411
Filesystem 412
File permissions 413
Flags and arguments 416
Signals 418
Exercise 14.01 – simulating a cleanup 422
Create and write to files 424
Reading the whole file at once 428
Exercise 14.02 – backing up files 430
CSV 436
Embedding 438
Summary 440
15
SQL and Databases 441
Technical requirements 441
Introduction 441
Understanding the database 442
Installing and configuring Postgres SQL 442
Database API and drivers 444
Connecting to databases 445
Creating a new project 446
Creating tables 449
Inserting data 452
Exercise 15.01 – creating a table that holds a
series of numbers 454
Retrieving data 456
Updating existing data 459
Deleting data 461
Exercise 15.02 – holding prime numbers
in a database 462
Truncating and deleting table 465
Activity 15.01 – holding user data in a table 466
Activity 15.02 – finding the messages of
specific users 467
Adding users with GORM 468
Finding Users with GORM 470
Summary 472
Part 5: Building For The Web
16
Web Servers 475
Technical requirements 475
Introduction 475
How to build a basic server 476
HTTP handler 476
Exercise 16.01 – creating a Hello World server 477
Simple routing 479
Exercise 16.02 – routing our server 480
Handler versus handler function 482
Activity 16.01 – adding a page counter to an
HTML page 483
Adding middleware 485
Dynamic content 489
Exercise 16.03 – personalized welcome 489
Templating 491
Exercise 16.04 – templating our pages 493
Static resources 497
Exercise 16.05 – creating a Hello World server
using a static file 497
Getting some style 499
Exercise 16.06 – a stylish welcome 500
Getting dynamic 504
Activity 16.02 – external template 505
Embedding external files 506
Summary 508
17
Using the Go HTTP Client 511
Technical requirements 511
Introduction 511
The Go HTTP Client and its uses 512
Sending a request to a server 512
Exercise 17.01 – sending a GET request to a
web server using the Go HTTP Client 513
Structured data 515
Exercise 17.02 – using the HTTP Client with
structured data 516
Activity 17.01 – requesting data from a web
server and processing the response 518
Sending data to a server 519
Exercise 17.03 – sending a POST request to a
web server using the Go HTTP Client 519
Uploading files in a POST request 522
Exercise 17.04 – uploading a file to a web
server via a POST request 522
Custom request headers 526
Exercise 17.05 – using custom headers and
options with the Go HTTP Client 526
Activity 17.02 – sending data to a web server
and checking whether the data was received
using POST and GET 529
Summary 530
Part 6: Professional
18
Concurrent Work 533
Technical requirements 533
Introduction 533
Goroutines 534
Exercise 18.01 – using concurrent Goroutines 535
WaitGroup 537
Exercise 18.02 – experimenting with
WaitGroup 538
Race conditions 540
Atomic operations 541
Exercise 18.03 – an atomic change 542
Invisible concurrency 547
Channels 548
Exercise 18.04 – exchanging greeting
messages via channels 550
Exercise 18.05 – two-way message exchange
with channels 551
Exercise 18.06 – summing numbers from
everywhere 553
Exercise 18.07 – request to Goroutines 555
The importance of concurrency 556
Exercise 18.08 – equally splitting work
between Goroutines 557
Concurrency patterns 559
Buffers 559
Exercise 18.09 – notifying when the
computation has finished 563
Some more common practices 564
HTTP servers 565
Methods as Goroutines 565
Exercise 18.10 – a structured work 566
Go context package 568
Exercise 18.11 – managing Goroutines with
a context 569
Concurrent work with sync.Cond 571
Exercise 18.12 – creating a WIP limited queue 571
The thread-safe map 574
Exercise 18.13 – counting how many times
random numbers are between 0 and 9 using
sync.Map 574
Summary 576
19
Testing 579
Technical requirements 579
Introduction 579
Unit tests 580
Exercise 19.01 – table-driven tests 581
Integration tests 584
Exercise 19.02 – integration test with a database 585
E2E tests 587
HTTP testing 588
Exercise 19.03 – authentication integration
with a test server 589
Fuzz testing 591
Benchmarks 592
Test suites 593
Exercise 19.04 – using TestMain to execute
several test functions 593
Test report 595
Code coverage 596
Summary 597
20
Using Go Tools 599
Technical requirements 599
Introduction 599
The go build tool 600
Exercise 20.01 – using the go build tool 600
The go run tool 601
Exercise 20.02 – using the go run tool 601
The gofmt tool 602
Exercise 20.03 – using the gofmt tool 602
The goimports tool 604
Exercise 20.04 – using the goimports tool 604
The go vet tool 606
Exercise 20.05 – using the go vet tool 606
The Go race detector 608
Exercise 20.06 – using the Go race detector 608
The go doc tool 611
Exercise 20.07 – implementing the go doc tool 611
The go get tool 613
Exercise 20.08 – implementing the go get tool 613
Activity 20.01 – using gofmt, goimport, go
vet, and go get to correct a file 614
Summary 616
21
Go in the Cloud 617
Technical requirements 617
Introduction 617
Making your app monitorable by
systems such as Prometheus 618
Exercise 21.01 – Creating an app with a /
healthz endpoint 620
Enabling deep insights through
OpenTelemetry 623
Exercise 21.02 – Using OpenTelemetry for
queryable logs and tracing 624
Best practices for putting your Go
application in a container 629
Exercise 21.03 – Creating a Dockerfile for a
Go application 630
Making your app ready to work with
orchestrators such as Kubernetes 632
Summary 633
Index 635
Other Books You May Enjoy 648