Go by Example (上 桷)

Github code: github.com/ftopia2020/…

Here are some examples of specific Golang development scenarios, including the following:

  • Some common methods for built-in packages (e.g., sort, time, IO, OS, FMT, JSON, XML, etc.)
  • Panic
  • Defer
  • Data parsing
  • File to read and write
  • Unit testing
  • Command line operation
  • HTTP client/server simple implementation
  • Build process/execute process
  • signal
  • exit

40 Sorting

The sort package implements four basic sorting algorithms: insert sort, merge sort, heap sort, and quicksort. However, these four sorting methods are not exposed and are only used for internal use within the SORT package. The sort package automatically selects an efficient sorting algorithm πŸ‚ based on the actual data

TX have time to look at the source code, sorting notes are very clear, but also added the complexity of πŸ‘

41 Sorting By Functions

Using custom function sorting: Create a custom type, implement the three methods of the Interface Interface (Len, Swap, Less) for it, and then call sort.sort on the custom type slice. We can sort the Go slice by any function.

42 Panic

Try creating a file folder under/TMP, comment out the first panic statement, and run again

Of course, you can also try deleting the file folder and run it later

A “Panic” exception is a serious problem, usually an error that must not occur during normal operation or that is not intended to be handled.

Panic can be recovered by using recover. For more information, see golang.org/doc/effecti…

The Go runtime code calls panic in many places, such as array subscript out of bounds, null pointer, etc

!!!!!!!!! Note that unlike some languages that use exception to handle errors, in Go it is common to use return values to indicate errors whenever possible.

43 Defer

Defer is used to ensure that a function is called when the program is finished executing, typically to perform cleanup. Defer is used ina similar way to Ensure or finally in other languages.

Also, recover can only be used in the defer statement, and calling recover directly is not effective

44 Collection Functions

We often need programs to perform operations on a collection of data, such as selecting all items that meet a given condition, or mapping all items to a new collection through a custom function.

In other languages, generic data structures and algorithms are often used. But Go does not support generics, and it is common to provide a set of functions if your program or data type requires one.

Here are some examples of combination functions for strings slices. You can use these examples to build your own functions. Note that, in some cases, it is straightforward to work directly on the set of methods inline rather than creating and calling helper functions.

45 String Functions

The Strings package provides a number of built-in string manipulation methods, which can be found at golang.org/pkg/strings…

You can use methods like import aliases and custom var to simplify the use of duplicate code

46 String Formatting

Go provides excellent support for string formatting in traditional fmt.printf; See golang.org/pkg/fmt/

47 Regular Expressions

Go provides built-in regular expression support. Here are some examples of common usage related to regexp in Go.

48 Json

Go provides built-in JSON encoding and decoding (serialization and deserialization) support, including conversion between built-in and custom types and JSON data.

For more information, check out the JSON and Go blog and JSON Package Docs.

In addition, using the “json sequence json.Marshal, then parse json.Unmarshal” method is a way to implement deep copy (clone) of objects.

!!!!! However, although it can basically handle most of the requirements, the disadvantages are low performance and various limitations, such as inability to handle recursive Pointers, inability to handle interface type data, loss of most data types and even accuracy.

49 XML

50 Time

Go provides extensive support for time and duration, as shown at golang.org/pkg/time/

51 Epoch

How do you do that with Go? Gets the number of seconds, milliseconds, or microseconds of Unix time

52 Time Formatting

Go supports formatting and parsing through time based description templates

Time parsing uses the same layout value as Format, and Parse returns a parsing error when the entered time Format is incorrect

53 Random Numbers

See the Math/RAND package documentation for additional random numbers that Go provides

54 Number Parsing

The general operation of Golang to parse numbers from a string; More details: golang.org/pkg/strconv…

55 URL Parsing

The built-in parsing method is provided by the NET/URL package, and later examples will also cover usage scenarios for the Golang NET package

56 SHA1 Hashes

You can calculate other forms of hash in a similar way. For example, to compute an MD5 hash, introduce crypto/ MD5 and use the md5.new () method

Note that if you need cryptographic security hashes, you need to take a closer look at cryptographic hash functions

57 Base64 Encoding

Go provides built-in support for Base64 codecs; The encoding strings for standard base64 encoding and URL Base64 encoding are slightly different (suffixes + and -), but both can be correctly decoded as raw strings

59 Writing Files

Here we adjust the order of the example, write the file first, then read the file

There are two ways to write dat1 and dat2 files in the example

  1. Ioutill. WriteFile to write a string directly to a file (0644 is FileMode)

  2. Os.create creates an empty file and opens it! Customary action: Call Close to the file immediately using defer

    • Write file in byte slice mode (10 is newline character)
    • f.WriteStringMethod writes a string

58 Reading Files

Overwrite what the example reads and reuse the file written by example 59

Now that you’ve seen how Golang handles file reads and writes, let’s look at its application to stdin and STdout streams

60 Line Filters

After running the input arbitrary, view the output print

Wrapping unbuffered OS.stdin with buffered scanner gives us a convenient Scan method to advance scanner to the next token (default: next line)

61 File Paths

The Filepath package provides convenient cross-operating system parsing and building functions for file paths

62 Directories

Comment out the code for deleting the subdir folder to view the folder you created and the files underneath it

Go provides several useful functions for manipulating directories in a file system

63 Temporary Files and Directories

The easiest way to create a temporary file is to call the ioutil.TempFile function. It creates and opens files that we can read and write. Ioutil. TempFile is created in the default location of the operating system.

Defer deletes the file. Although the operating system automatically cleans up temporary files at some point, manual cleanup is a good habit.

64 Testing

Unit testing is an important part of writing a good Go program. The Testing package provides the tools needed to write unit tests, which can then be run using the Go test command.

More about unit testing content, suggest to consult the books.studygolang.com/The-Golang-…

The following example adjusts the corresponding file name:

  • Code to be tested: Intutils.go

  • The corresponding test file is intutils_test.go

For demonstration purposes, the code for the example is in the main package; in fact, the code for the unit test can be in any package. The test code is usually in the same package as the code that needs to be tested.

You can try deliberately changing part of the test data to be wrong and then see the results.

$ go test			# Run tests
$ go test -v	Run tests print detailed use case run results
#For more information, run gohelp testAnd gohelpTestflag understand
Copy the code

A few things to keep in mind about unit testing:

  • Test suite: the file whose name ends with _test.go containsTestXxxFunction, usually in the same package as the file under test
  • t.Error*A test failure message is reported and the test continues to run
  • t.Fail*A test failure is reported and the test is terminated immediately

65 Command Lines

$ go build 
Copy the code

Command-line arguments are a common way to specify program execution parameters. For example, go run hello.go, the program go takes run and hello.go

A new folder was created to hold the example, and the executable binaries were compiled by running go Build beforehand

Let’s look at more advanced command-line processing using tags

66 Command Line Flags

Command-line flags are a common way for command-line programs to specify options. For example, in WC -l, this -l is a command line flag

Go provides a flag package that supports basic command line flag parsing

A new folder was created to hold the example, and the executable binaries were compiled by running go Build beforehand

$ go build 66_command-line-flags.go # Build binaries
$ ./66_command-line-flags -word=opt -numb=7 -fork -svar=flag	# Assign values to all flags and try to run the built program
$ ./66_command-line-flags -word=opt # omit a flag, automatically set the default value
$ ./66_command-line-flags -word=opt a1 a2 a3 # Trailing positional parameters can appear after any flag
$ ./66_command-line-flags -word=opt a1 a2 a3 -numb=7 # Note that flag packets require all flags to appear before positional arguments (otherwise, flags will be parsed as positional arguments)
$ ./66_command-line-flags -h 	Use the -h or --help flag to get the help text for the automatically generated command line program
$ ./66_command-line-flags -wat # provides a flag that does not use the flag package declaration, and the program prints an error message and displays the help text again
Copy the code

67 Command Line Subcommands

Command line tools like go and Git have many subcommands. And each tool has its own set of flags, for example: Go build and Go Get are two different subcommands in Go. The Flag package makes it easy to define simple subcommands for tools

$ ./67_command-line-subcommands foo -enable -name=joe a1 a2		# call the foo subcommand
$ ./67_command-line-subcommands bar -level 8 a1		# Try the bar subcommand
$ ./67_command-line-subcommands bar -enable a1		# bar does not accept foo's flag (enable)
Copy the code

68 Environment Variables

Environment variables are a common way to pass configuration information to Unix programs. Let’s see how to set, get, and list environment variables

The list of keys depends on your computer

If we set the value of BAR before running, the program will get this value

69 HTTP Clients

The Go standard library’s NET/HTTP package provides excellent support for BOTH HTTP clients and servers

In this example, we will use it to send a simple HTTP request

70 HTTP Servers

Handlers are a basic concept in NET/HTTP servers. The handler object implements the HTTP.Handler interface. A common way to write a handler is to use the HTTP.handlerfunc adapter on functions that have the appropriate signature

The handler function takes two arguments, http.ResponseWriter and http.Request. Response Writer is used to write HTTP response data. Here we simply return “hello\n”.

The handler function takes two arguments, http.ResponseWriter and http.Request. Response Writer is used to write HTTP response data. Here we simply return “hello\n”.

Using the http.handlefunc function, we can easily register our handler to the server route. It is the default route in the NET/HTTP package and takes a function as an argument

Finally, we call ListenAndServe with the port and handler. Nil means to use the default router we just set up

In the screenshot, you can check the port usage of the local host (if the port is used by other applications, you can change the port usage) and curl accesses the Hello route

71 Context

Sometimes, the Go program needs to generate other, non-Go processes, and the OS /exec package makes it possible to run external commands

72 Execing Processes

We just want to completely replace the current Go process with another (perhaps non-Go) process. At this point, we can use the Go implementation of the classic exec function

73 Signals

Sometimes we want Go to handle Unix signals intelligently. For example, we want the server to exit gracefully when it receives a SIGTERM signal, or a command line tool to stop processing input when it receives a SIGINT signal. What we’re talking about here is how channels are used to process signals in Go.

74 Exit

Use os.exit to immediately Exit the program with a given state