1. fmt formatter package
Introduction to the fmt package: fmt = format is a formatted output function summary package for formatted output.
Println、Print、Printf
fmt.Print output as is
Print formats using the default formats for its operands and writes to standard output.
start := time.Now()
fmt.Print(start)
// 2023-01-12 16:50:00.2675807 +0800 CST m=+0.002138901
fmt.Printf format output
Printf formats according to a format specifier and writes to standard output.
Print the output according to the format, Printf = Print format usage:
fmt.Printf("%格式1 %格式2", 变量值1, 变量2)
Format placeholder type: %s
: string, %d
: decimal value, %T
: type(value)
For example, the code display of printing variable address value:
var a int = 1
fmt.Printf("the addr of a is %p", &a)
the addr of a is 0xc00015bf58
fmt.Println value + space output
Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended.
const name, age = "Kim", 22
fmt.Println(name, age)
Scan console input
The usage of the Scan series functions that obtain data from standard input in the fmt package in Go language, the Fscan series functions that obtain data from io.Reader, and the Sscan series functions that obtain data from strings.
There are three functions under the fmt package of Go language, fmt.Scan, fmt.Scanf, and fmt.Scanln, which can obtain user input from standard input during program running.
func Scan(a ...interface{
}) (n int, err error)
Scan scans the text from the standard input, reads the values separated by blanks and saves them in the parameters passed to this function, newlines are treated as blanks. This function returns the number of data successfully scanned and any errors encountered. If the number of data read is less than the provided parameter, an error will be returned to report the reason.
var a int
fmt.Println("a = ")
fmt.Scanln(&a)
fmt.Println("a = " + strconv.Itoa(a))
2. time time date package
Package time provides functionality for measuring and displaying time.
The calendrical calculations always assume a Gregorian calendar, with no leap seconds.
Calendar calculations always use the Gregorian calendar, without leap seconds.
Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.
The operating system provides a "wall clock" that changes due to clock synchronization and a "monotonic clock" that does not. The general rule is that wall clocks are for telling time and monotonic clocks are for measuring time. In this package, Time is returned by time instead of split API. Now contains a wall clock reading and a monotonic clock reading; later timekeeping operations use the wall clock reading, but later time measurement operations, especially comparisons and subtractions, use the monotonic clock reading.
func Sleep pause time
Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.
Sleep suspends the current gorroutine for at least duration d. A negative or zero duration will cause Sleep to return immediately.
func Sleep(d Duration)
Sleep case show:
var timer int = 0
for i := 0; i < 100; i++ {
fmt.Printf("now timer is %d items \n", timer)
time.Sleep(1000 * time.Millisecond)
timer++
}
func ParseDuration parse duration string
ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as “300ms”, “-1.5h” or “2h45m”. Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”.
ParseDuration parses a duration string. A duration string is a possible sequence of decimal digit symbols, each with an optional fraction and unit suffix, such as "300ms", "-1.5h", or "2h45m".
duration, err := time.ParseDuration("1h20m30s")
fmt.Printf("err value is : %T", err)
// err value is : err
fmt.Println("Hour time is ", duration.Hours())
// Hour time is 1.3416666666666668
func AfterFunc(d Duration, f func()) *Timer
AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.
Whether it is business development or infrastructure development, timers cannot be bypassed, which shows the importance of timers.
Whether we use NewTimer, timer.After, or timer.AfterFun to initialize a timer, this timer will eventually be added to a global timer heap, which is managed by the Go runtime.
time.format() time formatting
When using time.Format to format the time parameter layout, "2006-01-02 15:04:05" must be passed. Why?
North American Mountain Time (MST: Mountain Standard Time) on January 2, 2006 (PM) at 3:4:5. Many people say that this is Golang's narcissistic behavior, because it is rumored that this is when the Go language was born, but at its root, this is not the case.
If you observe carefully, you will find that, in fact, the time arrangement is as follows:
1,2,3,4,5,6,7
Corresponding in turn: (The forms in brackets are acceptable, PM can be uppercase or lowercase, the month can only be capitalized with the first letter, and the order is not limited, but there must be separators in the form of spaces, "-", "|" and other forms between them)
There is no reason, this is the most pitiful place. It is said that this date is the birth time of the GO language. This date must be passed when formatting, and other times will have problems.
func main() {
for i := 0; i < 100000; i++ {
now := time.Now()
formatTime := now.Format("2006-01-02 03:04:05")
fmt.Println("227622890 注销倒计时:" + formatTime)
time.Sleep(1000 * time.Millisecond)
}
}
3. os operating system package
Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.
The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall.
WriteString writes a string
Use the os package for file writing operations, the code shows:
file, err := os.OpenFile("helloworld.txt", syscall.O_RDWR|syscall.O_CREAT, 0)
if err != nil {
os.Exit(1)
}
defer file.Close()
file.WriteString("hello world. Nice to see you.")
If the open fails, the error string will be self-explanatory, like
open file.go: no such file or directory
os.FileMode(0600) File permissions: Windows system permissions are invalid.
Fatal is equivalent to Print() followed by a call to os.Exit(1).
Fatal is equivalent to calling os.Exit(1) after Print().
Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
The remaining values may be or’ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
Read read data
The file’s data can then be read into a slice of bytes. Read and Write take their byte counts from the length of the argument slice.
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])
defer statement
The defer statement in the go language will delay the processing of the following statements. When the function to which defer belongs is about to return, the deferred statements are executed in the reverse order defined by defer, that is to say, the statement that is defer first is executed last, and the statement that is defer last is executed first.
defer is generally used to release resources and catch exceptions, as one of the features of the Go language.
The defer statement will delay the processing of the following statements. It means that the language following defer will be executed after the program makes the final return.
When the function to which defer belongs is about to return, the deferred statements will be executed in the reverse order of defer, that is to say, the statement defered first will be executed last, and the statement defered last will be executed first.
4. net network programming package
Package http provides HTTP client and server implementations.
Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{
"key": {
"Value"}, "id": {
"123"}})
ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux:
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
Case display:
package main
import (
"io"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<h1>hello world</h1>")
}
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8080", nil)
}
The client must close the response body when finished with it:
resp, err := http.Get("https://api.vvhan.com/api/weather?city=杭州")
if err != nil {
os.Exit(1)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
os.Stdout.Write(body)
Display response status code: for example: 200
println(resp.StatusCode)
The http package’s Transport and Server both automatically enable HTTP/2 support for simple configurations. To enable HTTP/2 for more complex configurations, to use lower-level HTTP/2 features, or to use a newer version of Go’s http2 package, import “golang.org/x/net/http2” directly and use its ConfigureTransport and/or ConfigureServer functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 package takes precedence over the net/http package’s built-in HTTP/2 support.
5. strconv type conversion package
The strconv package in the Go language realizes the conversion between basic data types and their string representations.
The strconv package realizes the conversion between basic data types and their string representations, mainly including the following commonly used functions: Atoi(), Itia(), parse series, format series, append series.
string and int type conversion
int conversion string: Itoa()
println("a" + strconv.Itoa(32))
string to int: Atoi()
i, _ := strconv.Atoi("3")
println(1 + i)
i, err := strconv.Atoi("a")
if err != nil {
println("converted failed")
}
Parse class functions
The Parse class functions are used to convert a string to a value of a given type: ParseBool(), ParseFloat(), ParseInt(), ParseUint().
b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)
ParseInt() and ParseUint() have 3 parameters
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (uint64, error)
bitSize参数
An int/uint indicating what bits to convert to, valid values are 0, 8, 16, 32, 64. When bitSize=0, it means converting to int or uint type. For example, bitSize=8 indicates that the type of the converted value is int8 or uint8.
base参数
Indicates in what base to parse the given string, valid values are 0, 2 ~ 36. When base=0, it means to judge what base to parse according to the prefix of the string: those starting with 0x are parsed in hexadecimal, those starting with 0 are parsed in octal, and others are parsed in decimal way to parse.
Format class function
Format the given type as string: FormatBool(), FormatFloat(), FormatInt(), FormatUint().
s := strconv.FormatBool(true)
s := strconv.FormatFloat(3.1415, 'E', -1, 64)
s := strconv.FormatInt(-42, 16)
// 表示将-42转换为16进制数,转换的结果为-2a。
s := strconv.FormatUint(42, 16)
The second parameter base specifies how many bases to convert the first parameter to, and the valid value is 2<=base<=36
. When the specified base is greater than 10, the values beyond 10 a-z
are represented by letters. For example, in the hexadecimal system, the numbers 10-15 are represented by numbers a-f
, and in the hexadecimal system, the values of 10-16 are represented by the numbers respectively a-g
.
FormatFloat() function:
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
bitSize
Indicates the source type of f (32: float32, 64: float64), which will be rounded accordingly.
fmt
Representation format: 'f' (-ddd.dddd), 'b' (-ddddp±ddd, exponent is binary), 'e' (-d.dddde±dd, decimal exponent), 'E' (-d.ddddE ±dd, decimal exponent), 'g' (use 'e' format for large exponent, otherwise 'f' format), 'G' (use 'E' format for large exponent, otherwise 'f' format).
prec
Control precision (excluding the exponent part): for 'f', 'e', 'E', it indicates the number of digits after the decimal point; for 'g', 'G', it controls the total number of digits. If prec is -1, it means to use the minimum number of required numbers to represent f.
6. mongo database package
MongoDB is a high-performance, open-source, schema-free document database. It is a product between relational databases and non-relational databases. It is the most functional and most similar to relational databases among non-relational databases. The data structure it supports is very loose, and it uses the json-like bjson format to store data, so it can store more complex data types.
The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to object-oriented query language. It can almost realize most of the functions similar to single-table query of relational database, and it also supports indexing of data.
Add mongodb dependency
go get go.mongodb.org/mongo-driver/mongo
Connect to MongoDB
link databasefunc Connect(ctx context.Context, opts ...*options.ClientOptions)
Connect requires two parameters, a context and an options.ClientOptions object
Simple link example:
// 设置客户端选项
clientOptions := options.Client().ApplyURI("mongodb://user:password@localhost:27017")
// 连接 MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// 检查连接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")