唤醒手腕 Go 语言常见第三方包、SDK 内置包函数用法教程(更新中)

1. fmt 格式化 包

fmt 包的介绍:fmt = format,是一种格式化输出函数汇总包,用于格式化输出。

Println、Print、Printf

在这里插入图片描述
fmt.Print 原样输出

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 格式输出

Printf formats according to a format specifier and writes to standard output.

根据格式打印输出,Printf = Print format 使用方法:

fmt.Printf("%格式1 %格式2", 变量值1, 变量2)

格式占位符类型:%s : 字符串、%d : 10进制数值、%T : type(值)

在这里插入图片描述
例如打印变量地址值 代码展示:

var a int = 1
fmt.Printf("the addr of a is %p", &a)

the addr of a is 0xc00015bf58

fmt.Println 值 + 空格 输出

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 控制台输入

Go语言中fmt包中从标准输入获取数据的的Scan系列函数、从io.Reader中获取数据的Fscan系列函数以及从字符串中获取数据的Sscan系列函数的用法。

Go语言fmt包下有fmt.Scan、fmt.Scanf、fmt.Scanln三个函数,可以在程序运行过程中从标准输入获取用户的输入。

func Scan(a ...interface{
    
    }) (n int, err error)

Scan从标准输入扫描文本,读取由空白符分隔的值保存到传递给本函数的参数中,换行符视为空白符。本函数返回成功扫描的数据个数和遇到的任何错误。如果读取的数据个数比提供的参数少,会返回一个错误报告原因。

var a int
fmt.Println("a = ")
fmt.Scanln(&a)
fmt.Println("a = " + strconv.Itoa(a))

2. time 时间日期 包

Package time provides functionality for measuring and displaying time.

The calendrical calculations always assume a Gregorian calendar, with no 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.

操作系统提供了一个“挂钟”和一个“单调钟”,前者会因为时钟同步而发生变化,后者则不会。一般的规则是挂钟是用来报时的,单调钟是用来测量时间的。在这个包中,Time按时间返回,而不是拆分API。现在包含一个挂钟读数和一个单调时钟读数;后来的报时操作使用挂钟读数,但后来的时间测量操作,特别是比较和减法,使用单调的时钟读数。

func Sleep 暂停时间

Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.

Sleep将当前的gorroutine暂停至少持续时间d。持续时间为负值或零将导致Sleep立即返回。

func Sleep(d Duration)

Sleep 案例展示:

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 解析持续时间字符串

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解析持续时间字符串。持续时间字符串是可能的十进制数字符号序列,每个序列都有可选的分数和单位后缀,例如“300ms”、“-1.5h”或“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.

定时器不管是业务开发,还是基础架构开发,都是绕不过去的存在,由此可见定时器的重要程度。

我们不管用 NewTimer, timer.After,还是 timer.AfterFun 来初始化一个 timer, 这个 timer 最终都会加入到一个全局 timer 堆中,由 Go runtime 统一管理。

time.format() 时间格式化

使用time.Format格式化时间参数layout必须要传"2006-01-02 15:04:05",为什么呢?

在这里插入图片描述
北美山地时间(MST:Mountain Standard Time)2006年1月2日下午(PM)3点4分5秒这个时间。许多人都说,这是Golang的自恋行为,因为传言说这就是Go语言诞生的时间,但是究其根源,其实并不是这样。
如果你仔细观察就会发现,其实这个时间排列一下就是:

1234567

依次对应:(括号内的形式均可,PM大小写均可,月份只能首字母大写,顺序不限,但他们之间必须要有空格、“-”、"|"等形式的分割符)

没有为什么,这就是最坑的地方,据说这个日期是GO语言的诞生时间,格式化时就必须要传这个时间,传其他的时间都会有问题。

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 操作系统 包

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 写入字符串

使用 os 包进行文件写入操作,代码展示:

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) 文件权限:windows系统权限失效。

Fatal is equivalent to Print() followed by a call to os.Exit(1).
Fatal等价于Print()之后调用os.Exit(1)。

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 读取数据

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 语句

go语言中的defer语句会将其后面跟随的语句进行延迟处理。在defer归属的函数即将返回时,将延迟处理的语句按defer定义的逆序进行执行,也就是说,先被defer的语句最后被执行,最后被defer的语句,最先被执行。

defer一般用于资源的释放和异常的捕捉, 作为Go语言的特性之一。

defer 语句会将其后面跟随的语句进行延迟处理。意思就是说 跟在defer后面的语言 将会在程序进行最后的return之后再执行.

在 defer 归属的函数即将返回时,将延迟处理的语句按 defer 的逆序进行执行,也就是说,先被 defer 的语句最后被执行,最后被 defer 的语句,最先被执行。

4. net 网络编程 包

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))

案例展示:

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)

展示 response 状态码:例如: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 类型转换 包

Go语言中strconv包实现了基本数据类型和其字符串表示的相互转换。

strconv 包实现了基本数据类型与其字符串表示的转换,主要有以下常用函数: Atoi()、Itia()、parse系列、format系列、append系列。

string 与 int 类型转换

int 转换 字符串:Itoa()

println("a" + strconv.Itoa(32))

string 转换 int:Atoi()

i, _ := strconv.Atoi("3")
println(1 + i)

i, err := strconv.Atoi("a")
if err != nil {
    
    
    println("converted failed")
}

Parse类函数

Parse类函数用于转换字符串为给定类型的值: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()和ParseUint()有3个参数

func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (uint64, error)

bitSize参数 表示转换为什么位的int/uint,有效值为0、8、16、32、64。当bitSize=0的时候,表示转换为int或uint类型。例如bitSize=8表示转换后的值的类型为int8或uint8。

base参数 表示以什么进制的方式去解析给定的字符串,有效值为0、2 ~ 36。当base=0的时候,表示根据string的前缀来判断以什么进制去解析:0x开头的以16进制的方式去解析,0开头的以8进制方式去解析,其它的以10进制方式解析。

Format类函数

将给定类型格式化为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)

第二个参数base指定将第一个参数转换为多少进制,有效值为 2<=base<=36。当指定的进制位大于10的时候,超出10的数值以a-z字母表示。例如16进制时,10-15的数字分别使用a-f表示,17进制时,10-16的数值分别使用a-g表示。

FormatFloat() 函数:

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

bitSize表示f的来源类型(32:float32、64:float64),会据此进行舍入。

fmt表示格式:‘f’(-ddd.dddd)、‘b’(-ddddp±ddd,指数为二进制)、‘e’(-d.dddde±dd,十进制指数)、‘E’(-d.ddddE±dd,十进制指数)、‘g’(指数很大时用’e’格式,否则’f’格式)、‘G’(指数很大时用’E’格式,否则’f’格式)。

prec控制精度(排除指数部分):对’f’、‘e’、‘E’,它表示小数点后的数字个数;对’g’、‘G’,它控制总的数字个数。如果prec 为-1,则代表使用最少数量的、但又必需的数字来表示f。

6. mongo 数据库 包

MongoDB是一个高性能,开源,无模式的文档型数据库,是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,采用的是类似json的bjson格式来存储数据,因此可以存储比较复杂的数据类型。

Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向 对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

添加mongodb依赖

go get go.mongodb.org/mongo-driver/mongo

连接MongoDB

链接数据库 func Connect(ctx context.Context, opts ...*options.ClientOptions)

Connect 需要两个参数,一个context和一个options.ClientOptions对象

简单的链接实例:

// 设置客户端选项
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!")

猜你喜欢

转载自blog.csdn.net/qq_47452807/article/details/128662711
今日推荐