Go Basic: Understanding Time, Epoch, Time Formatting Parsing, Random Numbers, Number Parsing, URL Parsing, sha256 Hashes, base64 Encoding in Go

Let’s dive into Advanced manipulation and formatting of data.

full lessons here👇:
https://programmerscareer.com/golang-basic-skill/

Generated by AI, there may be errors, for reference only

Topic 1.1: Time, Clock and Epoch in Golang

In Golang, we use the time package to work with date and time. This package provides a Time type that lets us manipulate dates and times in a variety of ways.

Now, you may ask, what is “epoch time”? Epoch or Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds; the Unix epoch is 00:00:00 UTC on 1 January 1970.

Let’s look at a quick example :

1
2
3
4
5
6
7
8
9
10
11
12
13
package main  

import (
"fmt"
"time"
)

func main() {
now := time.Now() // current local time
fmt.Printf("It's currently %s\n", now.String())
epoch := now.Unix()
fmt.Printf("That's %v seconds since the epoch\n", epoch)
}

In the above code, time.Now() function returns the current date and time, And the Unix() function returns the local Time’s seconds elapsed since January 1, 1970 UTC.

You might have noticed, to format the time we used “String()” function. In the next topic, we’ll discuss more about Time Formatting and Parsing.

Topic 1.2: Time Formatting and Parsing in GoLang

Golang uses a unique approach to format and parse time. The layout string used by the GoLang is actually the time Mon Jan 2 15:04:05 MST 2006, which was the time when the original Unix developers at AT&T chose the epoch to start (i.e., zero time, obliquely, 01/02 03:04:05PM '06 -0700).

No worries if it seems a bit unconventional. You’ll get used to it with a bit of practice.

To format time we use Time.Format(layout string) string function, and to parse time we use time.Parse(layout, value string) (Time, error) function.

Here is an explanatory example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main  

import (
"fmt"
"time"
)

func main() {
// Get current time
now := time.Now()
// Format date
fmt.Println("Formatted Date:", now.Format("02-Jan-2006"))
// Format datetime
fmt.Println("Formatted Datetime:", now.Format("02-Jan-2006 15:04:05"))
// Parse date
date, _ := time.Parse("02-Jan-2006", "13-Feb-2023")
fmt.Println("Parsed Date:", date)
}

In the above example, we are formatting current date and time to DD-MMM-YYYY and DD-MMM-YYYY HH:MI:SS formats, then parsing a date string to time.

Things will get clearer with usage.

Topic 1.3: Introduction to Random Numbers in Golang

Generating random numbers is a common task in many applications. In GoLang, we use the math/rand package for this purpose.

Here is an example of how you can generate a random integer in GoLang:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main  

import (
"fmt"
"math/rand"
"time"
)

func main() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// Generate a random integer
fmt.Println(rand.Intn(100))
}

In this code, we first seed the random number generator with the current time. This is necessary because, by default, Go’s random number generator always produces the same sequence of numbers. Seeding it with the current time ensures we get a different sequence each time our program runs.

Then we generate a random integer with rand.Intn(n int) int. This returns a random integer in the range [0, n). So, rand.Intn(100) will return a random integer between 0 and 99.

Generating random floats or generating random numbers within a range, uses a similar principle but with different functions.

Topic 1.4: Parsing Numbers in GoLang

Go provides built-in support for parsing numbers from strings. We can parse integers using the strconv package’s Atoi function and floats with ParseFloat.

Let’s take a look at this in action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main  

import (
"fmt"
"strconv"
)

func main() {
// Parsing string to int
i, _ := strconv.Atoi("10")
fmt.Println("Integer:", i)
// Parsing string to float64
f, _ := strconv.ParseFloat("3.14", 64)
fmt.Println("Float:", f)
}

The Atoi function attempts to convert a string to an integer. If it succeeds, it returns the integer and a nil error. If it fails, it returns zero and an error describing the problem.

Similarly, the ParseFloat function attempts to convert a string to a float. The second argument to ParseFloat represents the bit size of the float type.

One thing you need to remember, error handling is an important aspect while parsing.

Topic 1.5: URL Parsing in GoLang

In GoLang, URLs are parsed using the net/url package. The url.Parse()function is used to parse a URL and return a pointer to a URL structure. If successful, the returned URL object’s HostPathRawQuery and other fields give access to the various parts of the URL.

Here is a simple example demonstrating URL parsing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main  

import (
"fmt"
"net/url"
)

func main() {
u, err := url.Parse("http://test.com/path?a=1&b=2")
if err != nil {
panic(err)
}
fmt.Println(u.Scheme)
fmt.Println(u.Host)
fmt.Println(u.Path)
fmt.Println(u.RawQuery)
}

In this example, the URL.Parse() function parses the provided string url and gives out the struct as output.

Working with URLs is commonplace in many applications, so it’s a good idea to get comfortable with this.

Topic 1.6: Creating SHA256 Hashes in GoLang

In GoLang, the crypto/sha256 package is used to implement the SHA256 hash algorithm specifications laid out in FIPS 180-4.

A hash function maps data of arbitrary size to fixed size. Hash functions are deterministic, meaning they’ll give the same output every time for the same input.

The SHA (Secure Hash Algorithm) is one of a number of cryptographic hash functions. A cryptographic hash is like a signature for a text or a data file. SHA256 algorithm generates an almost-unique, fixed size 256-bit (32-byte) hash.

Here’s an example to hash a string using this package:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main  

import (
"crypto/sha256"
"fmt"
)
func main() {
s := "hello world"
h := sha256.New()
h.Write([]byte(s))
bs := h.Sum(nil)
fmt.Println(s)
fmt.Printf("%x\n", bs)
}

In the above example, we first create a new hash.Hash computing the SHA256 checksum. We then write our input string to it, and finally, call its Sum method to get the SHA256 checksum bytes.

The %x directive in Printf formats a byte slice into a hexadecimal string which gives us a nice viewable string of the hash.

Hashing is primarily used for comparing and storing sensitive data, like passwords, and ensuring data integrity.

Topic 1.7: Base64 Encoding in GoLang

Base64 encoding schemes are often used when there is a certain requirement to encode binary data, especially when that data needs to be stored and transferred over media that are designed to deal with text. This helps to ensure that the data remains uncorrupted without loss or modification during transport.

In GoLang, the encoding/base64 package provides functions to perform base64 encoding/decoding.

Here is an example of base64 encoding:

1
2
3
4
5
6
7
8
9
10
11
package main  

import (
"encoding/base64"
"fmt"
)
func main() {
data := "Hello, World!"
sEnc := base64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(sEnc)
}

In this example, we encode the string “Hello, World!” using the EncodeToString method of StdEncoding from the encoding/base64 package.

Now, here is a counterpart for decoding a base64 string:

1
2
3
4
5
6
7
8
9
10
11
12
package main  

import (
"encoding/base64"
"fmt"
)

func main() {
data := "SGVsbG8sIFdvcmxkIQ"
sDec, _ := base64.StdEncoding.DecodeString(data)
fmt.Println(string(sDec))
}

We decode the previously encoded string back to its original form using the DecodeString method of StdEncoding.

Base64 encoding is commonly used in a variety of applications including email via MIME, storing complex data in XML or JSON, and storing user credentials for web applications.

Topic 1.8: Review and Practice

For topics related to Time, Epoch, Time Formatting Parsing, Random Numbers, Number Parsing, and URL Parsing, I have a variety of exercises for you to practice:

  • Create a Go program that prints the current time in the format “Mon Jan 2 15:04:05 MST 2006”.
  • Write a program in Go that parses a user-provided date and time string and converts it into Epoch time.
  • Create a Go script to generate ’n’ random numbers where ’n’ can be any integer.
  • Write a function in Go that parses a string of comma-separated numbers and returns a slice of integers.
  • Create a program in Go that parses a URL and outputs the various components (scheme, domain, path, etc.).

For topics related to sha256 Hashes and base64 Encoding:

  • Write a Go function that takes an input string, computes its SHA256 hash, and returns it in base64 format.
  • Create a Go program that takes an input string, encodes it in base64, decodes it, and then verifies that the decoded string matches the original input.

Remember, it’s all about practice! These exercises are designed to help you get comfortable with these concepts and their implementations in Go. Can’t wait to see what solutions you come up with!

中文文章: https://programmerscareer.com/zh-cn/go-basic-12/
Author: Wesley Wei – Twitter Wesley Wei – Medium
Note: If you choose to repost or use this article, please cite the original source.

Go Basic: Understanding Testing and Benchmarking in Go Go Basic: Understanding Sorting, Text Templates, Regular Expressions, JSON, XML in Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×