Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Go Recipes for Developers
Go Recipes for Developers

Go Recipes for Developers: Top techniques and practical solutions for real-life Go programming problems

Arrow left icon
Profile Icon Burak Serdar
Arrow right icon
€8.99 €23.99
eBook Dec 2024 350 pages 1st Edition
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Burak Serdar
Arrow right icon
€8.99 €23.99
eBook Dec 2024 350 pages 1st Edition
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Go Recipes for Developers

Working with Strings

String is one of the fundamental data types in Go.

Go uses immutable UTF-8-encoded strings. This might be confusing for a new developer; after all, this works:

x:="Hello"
x+=" World"
fmt.Println(x)
// Prints Hello World

Didn’t we just change x? Yes, we did. What is immutable here are the "Hello" and " World" strings. So, the string itself is immutable, but the string variable, x, is mutable. To modify string variables, you create slices of bytes or runes (which are mutable), work with them, and then convert them back to a string.

UTF-8 is the most common encoding used for web and internet technologies. This means that any time you deal with text in a Go program, you deal with UTF-8 strings. If you have to process data in a different encoding, you first translate it to UTF-8, process it, and encode it back to its original encoding.

UTF-8 is a variable-length encoding that uses one to four bytes for each...

Creating strings

In this recipe, we will look at how to create strings in a program.

How to do it...

  • Use a string literal. There are two types of string literals in Go:
    • Use interpreted string literals, between the double quotations:
      x := "Hello world"
    • With interpreted string literals, you must escape certain characters:
      x:="This is how you can include a \" in your string literal"
      y:="You can also use a newline \n, tab \t"
    • You can include Unicode codepoints or hexadecimal bytes, escaped with '\':
      w:="\u65e5本\U00008a9e"
      x:="\xff"

You cannot have newlines or an unescaped double-quote in an interpreted string:

  • Use raw string literals, using backticks. A raw string literal can include any characters (including newlines) except a backtick. There is no way to escape backticks in a raw literal.
    x:=`This is a
    multiline raw string literal.
    Backslash will print as backslash \`

If you need to include...

Formatting strings

The Go standard library offers multiple ways to substitute values in a text template. Here, we will discuss the text formatting utilities in the fmt package. They offer a simple and convenient way to substitute values in a text template.

How to do it...

  • Use the fmt.Print family of functions to format values
  • fmt.Print will print a value using its default formatting
  • A string value will be printed as is
  • A numeric value will be first converted to a string as an integer, a decimal number, or by using scientific notation for large exponents
  • A Boolean value will be printed as true or false
  • Structured values will be printed as a list of fields

If a Print function ends with ln (such as fmt.Println), a new line will be output after the string.

If a Print function ends with f, the function will accept a format argument, which will be used as the template into which it will substitute values.

fmt.Sprintf will format a string and return...

Combining strings

The Go standard library offers multiple ways to build strings from components. The best way depends on what type of strings you are dealing with, and how long they are. This section shows several ways that strings can be built.

How to do it...

  • To combine a few fixed numbers of strings, or to add runes to another string, use the + or += operators or string.Builder
  • To build a string algorithmically, use strings.Builder
  • To combine a slice of strings, use strings.Join
  • To combine parts of URL paths, use path.Join
  • To build filesystem paths from path segments, use filepath.Join

How it works...

To build constant values, or for simple concatenations, use the + or += operators:

var TwoLines = "This is the first line \n"+
"This is the second line"
func ThreeLines(newLine string) string {
   return TwoLines+"\n"+newLine
}

You can add runes to a string the same way:

func AddNewLine(line string...

Working with string cases

When working with textual data, problems related to string cases arise often. Should a text search be case-sensitive or case-insensitive? How do we convert a string to lowercase or uppercase? In this section, we will look at some recipes to deal with these common problems in a portable way.

How to do it...

  • Convert strings to uppercase and lowercase using the strings.ToUpper and strings.ToLower functions, respectively.
  • When dealing with text in languages with special uppercase/lowercase mappings (such as Turkish, where “İ” is the uppercase version of “I”), use strings.ToUpperSpecial and strings.ToLowerSpecial
  • To convert text to uppercase for use in titles, use strings.ToTitle
  • To compare strings lexicographically, use comparison operators
  • To test the equivalence of strings ignoring case, use strings.EqualFold

How it works...

Converting a string to uppercase or lowercase is easy:

greet...

Working with encodings

If there is a chance that your program will have to work with data produced by disparate systems, you should be aware of different text encodings. This is a huge topic, but this section should provide some pointers to scratch the surface.

How to do it...

  • Use the golang.org/x/text/encoding package to deal with different encodings.
  • To find an encoding by name, use one of the following:
    • golang.org/x/text/encoding/ianaindex
    • golang.org/x/text/encoding/htmlindex
  • Once you have an encoding, use it to translate text to and from UTF-8.

How it works...

Use one of the indexes to find an encoding. Then, use that encoding to read/write data:

package main
import (
     "fmt"
     "os"
     "golang.org/x/text/encoding/ianaindex"
)
func main() {
     enc, err := ianaindex.MIME.Encoding("US-ASCII")
  ...

Iterating bytes and runes of strings

Go strings can be seen as a sequence of bytes, or as a sequence of runes. This section shows how you can iterate a string either way.

How to do it...

To iterate the bytes of a string, use indexes:

for i:=0;i<len(str);i++ {
  fmt.Print(str[i]," ")
}

To iterate the runes of a string, use range:

for index, c:=range str {
  fmt.Print(c," ")
}

How it works...

A Go string is a slice of bytes, so you would expect to be able to write a for-loop to iterate the bytes and runes of a string. You might think that you can do the following:

strBytes := []byte(str)
strRunes := []rune(str)

However, converting a string to a slice of bytes or a slice of runes is an expensive operation. The first one creates a writeable copy of the bytes of the str string, and the second one creates a writeable copy of the runes of str. Remember that rune is uint32.

There are two forms of for-loop to iterate the...

Splitting

The strings package offers convenient functions to split a string to get a slice of strings.

How to do it...

  • To split a string into components using a delimiter, use strings.Split.
  • To split the space-separated components of a string, use strings.Fields.

How it works...

If you need to parse a string delimited with a fixed delimiter, use strings.Split. If you need to parse the space-separated sections of a string, use strings.Fields:

package main
import (
     "fmt"
     "strings"
)
func main() {
     fmt.Println(strings.Split("a,b,c,d", ","))
    // ["a", "b", "c", "d"]
     fmt.Println(strings.Split("a, b, c, d", ","))
    // ["a", " b", " c", " d"]
   &...

Reading strings line by line, or word by word

There are many use cases for processing strings in a stream, such as when dealing with large text or user input. This recipe shows the use of bufio.Scanner for this purpose.

How to do it...

  • Use bufio.Scanner for reading lines, words, or custom blocks.
  • Create a bufio.Scanner instance
  • Set the split method
  • Read scanned tokens in a for-loop

How it works...

The Scanner works like an iterator – every call to Scan() method will return true if it parsed the next token, or false if there are no more tokens. The token can be obtained by the Text() method:

package main
import (
     "bufio"
     "fmt"
     "strings"
)
const input = `This is a string
that has 3
lines.`
func main() {
     lineScanner := bufio.NewScanner(strings.NewReader(input))
     line...

Trimming the ends of a string

User input is usually messy, including additional spaces before or after the text that matters. This recipe shows how to use the string trimming functions for this purpose.

How to do it...

Use the strings.Trim family of functions, as shown here:

package main
import (
     "fmt"
     "strings"
)
func main() {
     fmt.Println(strings.TrimRight("Break-------", "-"))
    // Break
     fmt.Println(strings.TrimRight("Break with spaces-- -- --", "- "))
    // Break with spaces
     fmt.Println(strings.TrimSuffix("file.txt", ".txt"))
    // file
     fmt.Println(strings.TrimLeft(" \t   Indented text", " \t"))
    ...

Regular expressions

A regular expression offers efficient methods to ensure that textual data matches a given pattern, searches for patterns, extracts, and replaces parts of text. Usually, you compile a regular expression once and then use that compiled regular expression many times to efficiently validate, search, extract, or replace parts of strings.

Validating input

Format validation is the process of ensuring that data coming from user input or other sources is in a recognized format. Regular expressions can be an effective tool for such validation.

How to do it...

Use precompiled regular expressions to validate input values that should fit a pattern.

package main
import (
     "fmt"
     "regexp"
)
var integerRegexp = regexp.MustCompile("^[0-9]+$")
func main() {
     fmt.Println(integerRegexp.MatchString("123"))   // true
  ...

Extracting data from strings

You can use a regular expression to locate and extract text that occurs within a pattern.

How to do it...

Use capture groups to extract substrings that match a pattern.

How it works...

package main
import (
     "fmt"
     "regexp"
)
func main() {
     re := regexp.MustCompile(`^(\w+)=(\w+)$`)
     result := re.FindStringSubmatch(`property=12`)
     fmt.Printf("Key: %s value: %s\n", result[1], result[2])
     result = re.FindStringSubmatch(`x=y`)
     fmt.Printf("Key: %s value: %s\n", result[1], result[2])
}

Here is the output:

Key: property value: 12
Key: x value: y

Let’s look at this regular expression:

  • ^(\w+): A string composed of one or more word characters at the beginning of the line (capture group 1)
  • ...

Replacing parts of a string

You can use a regular expression to search through text, replacing parts that match a pattern with other strings.

How to do it...

Use the Replace family of functions to replace the patterns in a string with something else:

package main
import (
     "fmt"
     "regexp"
)
func main() {
     // Find numbers, capture the first digit
     re := regexp.MustCompile(`([0-9])[0-9]*`)
     fmt.Println(re.ReplaceAllString("This example replaces 
     numbers  with 'x': 1, 100, 500.", "x"))
    // This example replaces numbers  with 'x': x, x, x.
     fmt.Println(re.ReplaceAllString("This example replaces all 
     numbers with their first digits: 1, 100, 500...

Templates

Templates are useful for generating data-driven textual output. The text/template package can be used in the following contexts:

  • Configuration files: You can accept templates in configuration files, such as the following example that uses an env map variable to create environment-sensitive configurations
    logfile: {{.env.logDir}}/log.json
  • Reporting: Use templates to generate output for command-line applications and reports
  • Web applications: The html/template package provides HTML-safe templating functionality for template-based HTML generation to build web applications

Value substitution

The main use of templates is inserting data elements into structured text. This section describes how you can insert values computed in a program into a template.

How to do it...

Use the {{.name}} syntax to substitute a value in a template.

The following code segment executes a template using different inputs:

package main
import (
    ...

Dealing with empty lines

Template actions (i.e., the code elements placed in a template) may result in unwanted empty spaces and lines. The Go template system offers some mechanisms to deal with these unwanted spaces.

How to do it...

Use - next to the template delimiter:

  • {{- will remove all spaces/tabs/newlines that were output before this template element
  • -}} will remove all spaces/tabs/newlines that come after this template element

If a template directive produces output, such as the value of a variable, it will be written to the output stream. But if a template directive does not generate any output, such as a {{range}} or {{if}} statement, then it will be replaced with empty strings. And if those statements are on a line by themselves, those lines will be written to the output as well, like this:

{{range .}}
  {{if gt . 1}}
    {{.}}
  {{end}}
{{end}}

This template will produce an output every four lines. When...

Template composition

As templates grow, they may become repetitive. To reduce such repetition, the Go template system offers named blocks (components) that can be reused within a template, just like functions in a program. Then, the final template can be composed of these components.

How to do it...

You can create template “components” that you can reuse in multiple contexts. To define a named template, use the {{define "name"}} construct:

{{define "template1"}}
  ...
{{end}}
{{define "template2"}}
 ...
{{end}}

Then, call that template using the {{template "name" .}} construct as if it is a function with a single argument:

{{template "template1" .}}
{{range .List}}
  {{template "template2" .}}
{{end}}

How it works...

The following example prints a book list using a named template:

package main
import (
     "os"
    ...

Template composition – layout templates

When developing web applications, it is usually desirable to have a few templates specifying page layouts. Complete web pages are constructed by combining page components, developed as independent templates using this layout. Unfortunately, the Go template engine forces you to think of alternative solutions because Go template references are static. This means you would need a separate layout template for each page.

But there are alternatives.

I’ll show you a basic idea that demonstrates how template composition can be used so that you can extend it, based on your use case, or how to use an available third-party library that does this. The crucial idea in composition using layout templates is that if you define a new template using an already-defined template name, the new definition overrides the older one.

How to do it...

  • Create a layout template. Use empty templates or templates with default content for the sections...

There’s more...

The Go standard library documentation is always your best source for up-to-date information and great examples, such as the following:

The following links are also useful:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Discover easy-to-implement recipes for all types of programming projects
  • Learn idiomatic solutions to common problems
  • Gain comprehensive knowledge of core Go concepts
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

With its simple syntax and sensible conventions, Go has emerged as the language of choice for developers in network programming, web services, data processing, and other settings. This practical guide helps engineers leverage Go through up-to-date recipes that solve common problems in day-to-day programming. Drawing from three decades of distributed systems engineering and technical leadership at companies like Red Hat, Burak Serdar brings battle-tested expertise in building robust, scalable applications. He starts by covering basics of code structure, describing different approaches to organizing packages for different types of projects. You’ll discover practical solutions to engineering challenges in network programming, dealing with processes, databases, data processing pipelines, and testing. Each chapter provides working solutions and production-ready code snippets that you can seamlessly incorporate into your programs while working in sequential and concurrent settings. The solutions leverage the more recent additions to the Go language, such as generics and structured logging. Most of the examples are developed using the Go standard library without any third-party packages. By the end of this book, you’ll have worked through a collection of proven recipes that will equip you accelerate your Go development journey.

Who is this book for?

This book is for any developer with a basic understanding of the Go language. If you’re a senior developer, you can use it as a reference for finding useful examples they can apply to different use cases.

What you will learn

  • Understand how to structure projects
  • Find out how to process text with Go tools
  • Discover how to work with arrays, slices, and maps
  • Implement robust error handling patterns
  • Explore concurrent data processing for Go programs
  • Get up to speed with how to control processes
  • Integrate Go applications with databases
  • Understand how to test, benchmark, and profile Go programs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2024
Length: 350 pages
Edition : 1st
Language : English
ISBN-13 : 9781835464786
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 30, 2024
Length: 350 pages
Edition : 1st
Language : English
ISBN-13 : 9781835464786
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
Banner background image

Table of Contents

19 Chapters
Chapter 1: Project Organization Chevron down icon Chevron up icon
Chapter 2: Working with Strings Chevron down icon Chevron up icon
Chapter 3: Working with Date and Time Chevron down icon Chevron up icon
Chapter 4: Working with Arrays, Slices, and Maps Chevron down icon Chevron up icon
Chapter 5: Working with Types, Structs, and Interfaces Chevron down icon Chevron up icon
Chapter 6: Working with Generics Chevron down icon Chevron up icon
Chapter 7: Concurrency Chevron down icon Chevron up icon
Chapter 8: Errors and Panics Chevron down icon Chevron up icon
Chapter 9: The Context Package Chevron down icon Chevron up icon
Chapter 10: Working with Large Data Chevron down icon Chevron up icon
Chapter 11: Working with JSON Chevron down icon Chevron up icon
Chapter 12: Processes Chevron down icon Chevron up icon
Chapter 13: Network Programming Chevron down icon Chevron up icon
Chapter 14: Streaming Input/Output Chevron down icon Chevron up icon
Chapter 15: Databases Chevron down icon Chevron up icon
Chapter 16: Logging Chevron down icon Chevron up icon
Chapter 17: Testing, Benchmarking, and Profiling Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.