Go基础语言初识 | 青训营笔记
这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记
1、Go语言简介
优势:
- 高性能、高并发
- 语法简单、学习曲线平缓
- 丰富的标准库
- 完善的工具链
- 静态链接
- 快速编译
- 跨平台
- 垃圾回收
2、入门——基础语法
-
Hello world基本框架
-
变量:
a := float() a int//两种声明变量类型的方式 const s //作为常量,const自动确定类型 -
if else
特点:循环要求中无括号
-
循环:
只有for循环,也是不用+()
continue——继续循环
break——跳出循环
-
switch——分支结构
-
数组
-
切片
-
map——完全无序
-
range
-
函数——变量类型后置
Go的特殊属性——Go语言支持多返回值,如果有错误信息则在最后一个返回值存储错误信息
-
指针——作用有限,对常用参数进行修改
-
结构体
-
结构体方法(两种)
-
带指针
对结构体进行修改
-
不带指针
-
-
错误处理——使用单独的返回值进行查找处理——加一个err(最后同时return两个值即可)
-
字符串操作——引入“strings包”
-
字符串格式化——“标准库fmt包”
-
JSON操作
-
时间处理——引入“time标准库”
-
数字解析——引入“strconv标准包”
-
进程信息
3、实战(三个实例)
实例一、猜数游戏
package main
import (
"fmt"
"bufio"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func main() {
maxNum := 100
rand.Seed(time.Now().UnixNano())
secretNumber := rand.Intn(maxNum)
// fmt.Println("The secret number is ", secretNumber)
fmt.Println("Please input your guess")
reader := bufio.NewReader(os.Stdin)
for {
input, err := reader.ReadString('\n')//读取一行的输入
if err != nil {
fmt.Println("An error occured while reading input. Please try again", err)
continue
}
input = strings.TrimSuffix(input, "\r\n")
guess, err := strconv.Atoi(input)//转换成数字
if err != nil {
fmt.Println("Invalid input. Please enter an integer value")
continue
}
fmt.Println("You guess is", guess)
if guess > secretNumber {
fmt.Println("Your guess is bigger than the secret number. Please try again")
} else if guess < secretNumber {
fmt.Println("Your guess is smaller than the secret number. Please try again")
} else {
fmt.Println("Correct, you Legend!")
break
}
}
}
代码解析
-
首先值得注意的是在
input = strings.TrimSuffix(input, "\r\n")此行代码中,由于是windows系统中的回车换行为:\r\n,而IOS或LINUX为:\n,因此该行代码的含义是去除input的换行符。 -
rand.Seed(time.Now().UnixNano())通过引入rand库,生成随机数种子,使得每次的随机数都不相同。 -
err != nil是一个异常处理,Go语言支持多返回值,如果有错误信息则在最后一个返回值存储错误信息,nil 是一个预定义常量,用来表示特定几个类型的变量的零值。
因此只有err == nil,才是正常输入。
-
下面介绍用到的几个Go语言标准库包
-
fmt
fmt包实现了类似C语言printf和scanf的格式化I/O。主要分为向外输出内容和获取输入内容两大部分。
-
bufio
bufio 包实现了缓存IO。它包装了 io.Reader 和 io.Writer 对象,创建了另外的Reader和Writer对象,它们也实现了io.Reader和io.Writer接口,不过它们是有缓存的。该包同时为文本I/O提供了一些便利操作。
-
math/rand
math库是一些数学运算库,其中包含的rand函数——生成随机数
-
os
计算机中的文件是存储在外部介质(通常是磁盘)上的数据集合,文件分为文本文件和二进制文件。
os 包中提供了操作系统函数的接口,是一个比较重要的包。顾名思义,os 包的作用主要是在服务器上进行系统的基本操作,如文件操作、目录操作、执行命令、信号与中断、进程、系统状态等等。有诸多常用函数……
-
strconv
Go语言中
strconv包实现了基本数据类型和其字符串表示的相互转换。
-
实例二、在线词典介绍
学习内容——调用第三方API查询翻译,Go语言发送Http请求,解析JSON,提高开发效率
举例API——彩云小译 - 在线翻译 (caiyunapp.com)
抓包(以edge浏览器为例)
-
页面右键,点击检查,出现开发者界面
-
输入英文点击翻译按钮——找到开发者工具一栏的网络(Network),在网络栏的名称部分找到
dict项,若有多个,挨个点击,看右侧标头显示请求方法是POST的。 -
再看负载、响应两栏的信息,如下图所示则正确
解析JSON
在Paylod一栏(负载)会出现两行信息
- source——即输入要翻译的内容
- trans_type——即要翻译的类型
-
在Goland中发送该Post
代码生成——利用工具自动生成Goland代码
点击该dict,选择复制——“复制为cURL(bash)”关键
-
打开该网址——Convert curl commands to code (curlconverter.com)
(代码生成)
在curl command中粘贴该请求,点击Go生成代码
复制粘贴后运行成功
-
生成代码解读(以注释形式)
package main import ( "fmt" "io/ioutil" "log" "net/http" "strings" ) func main() { client := &http.Client{}//创建对象 var data = strings.NewReader(`{"trans_type":"en2zh","source":"network","user_id":"621c8407237fc50011e1a8d9"}`) req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)//创建请求 if err != nil { log.Fatal(err) } req.Header.Set("Accept", "application/json, text/plain, */*") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") req.Header.Set("Connection", "keep-alive")//设置请求头(下同) req.Header.Set("Content-Type", "application/json;charset=UTF-8") req.Header.Set("Origin", "https://fanyi.caiyunapp.com") req.Header.Set("Referer", "https://fanyi.caiyunapp.com/") req.Header.Set("Sec-Fetch-Dest", "empty") req.Header.Set("Sec-Fetch-Mode", "cors") req.Header.Set("Sec-Fetch-Site", "cross-site") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39") req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi") req.Header.Set("app-name", "xy") req.Header.Set("os-type", "web") req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Microsoft Edge";v="101"`) req.Header.Set("sec-ch-ua-mobile", "?0") req.Header.Set("sec-ch-ua-platform", `"Windows"`) resp, err := client.Do(req)//发起请求 if err != nil { log.Fatal(err) } defer resp.Body.Close()//从下往上触发 bodyText, err := ioutil.ReadAll(resp.Body)//读取响应 if err != nil { log.Fatal(err) } fmt.Printf("%s\n", bodyText) } -
生成request body
即修改代码为
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) type DictRequest struct { TransType string `json:"trans_type"` Source string `json:"source"` UserID string `json:"user_id"` } func main() { client := &http.Client{} request := DictRequest{TransType: "en2zh", Source: "good"} buf, err := json.Marshal(request) if err != nil { log.Fatal(err) } var data = bytes.NewReader(buf) req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data) if err != nil { log.Fatal(err) } req.Header.Set("Accept", "application/json, text/plain, */*") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") req.Header.Set("Connection", "keep-alive") req.Header.Set("Content-Type", "application/json;charset=UTF-8") req.Header.Set("Origin", "https://fanyi.caiyunapp.com") req.Header.Set("Referer", "https://fanyi.caiyunapp.com/") req.Header.Set("Sec-Fetch-Dest", "empty") req.Header.Set("Sec-Fetch-Mode", "cors") req.Header.Set("Sec-Fetch-Site", "cross-site") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39") req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi") req.Header.Set("app-name", "xy") req.Header.Set("os-type", "web") req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Microsoft Edge";v="101"`) req.Header.Set("sec-ch-ua-mobile", "?0") req.Header.Set("sec-ch-ua-platform", `"Windows"`) resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() bodyText, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", bodyText) } -
解析response body
运用到了该网址——JSON转Golang Struct - 在线工具 - OKTools
点击原来dict的预览(Preview)的第一行——点击复制值
{ "rc": 0, "wiki": { "known_in_laguages": 92, "description": { "source": "collection of computers and other hardware interconnected by communication channels", "target": null }, "id": "Q1301371", "item": { "source": "computer network", "target": "计算机网络" }, "image_url": "http://www.caiyunapp.com/imgs/link_default_img.png", "is_subject": "false", "sitelink": "https://www.caiyunapp.com/read_mode/?id=6264987f90b04a1d614aea01" }, "dictionary": { "prons": { "en-us": "[ˈnεtˌwɝk]", "en": "[ˈnetwəːk]" }, "explanations": [ "n.网状物;网络,网状系统;广播网,电视网", "vt.覆以网络;使参加联播公司", "[计]进入网络系统", "vi.(与他人)沟通,互动" ], "synonym": [], "antonym": [], "wqx_example": [], "entry": "network", "type": "word", "related": [], "source": "wenquxing" } }将上述代码复制进网站——点击
转换—嵌套生成代码。type AutoGenerated struct { Rc int `json:"rc"` Wiki Wiki `json:"wiki"` Dictionary Dictionary `json:"dictionary"` } type Description struct { Source string `json:"source"` Target interface{} `json:"target"` } type Item struct { Source string `json:"source"` Target string `json:"target"` } type Wiki struct { KnownInLaguages int `json:"known_in_laguages"` Description Description `json:"description"` ID string `json:"id"` Item Item `json:"item"` ImageURL string `json:"image_url"` IsSubject string `json:"is_subject"` Sitelink string `json:"sitelink"` } type Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } type Dictionary struct { Prons Prons `json:"prons"` Explanations []string `json:"explanations"` Synonym []interface{} `json:"synonym"` Antonym []interface{} `json:"antonym"` WqxExample []interface{} `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface{} `json:"related"` Source string `json:"source"` }修改7. 代码——
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) type DictRequest struct { TransType string `json:"trans_type"` Source string `json:"source"` UserID string `json:"user_id"` } type DictResponse struct { Rc int `json:"rc"` Wiki Wiki `json:"wiki"` Dictionary Dictionary `json:"dictionary"` } type Description struct { Source string `json:"source"` Target interface{} `json:"target"` } type Item struct { Source string `json:"source"` Target string `json:"target"` } type Wiki struct { KnownInLaguages int `json:"known_in_laguages"` Description Description `json:"description"` ID string `json:"id"` Item Item `json:"item"` ImageURL string `json:"image_url"` IsSubject string `json:"is_subject"` Sitelink string `json:"sitelink"` } type Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } type Dictionary struct { Prons Prons `json:"prons"` Explanations []string `json:"explanations"` Synonym []interface{} `json:"synonym"` Antonym []interface{} `json:"antonym"` WqxExample []interface{} `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface{} `json:"related"` Source string `json:"source"` } func main() { client := &http.Client{} request := DictRequest{TransType: "en2zh", Source: "good"} buf, err := json.Marshal(request) if err != nil { log.Fatal(err) } var data = bytes.NewReader(buf) req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data) if err != nil { log.Fatal(err) } req.Header.Set("Accept", "application/json, text/plain, */*") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") req.Header.Set("Connection", "keep-alive") req.Header.Set("Content-Type", "application/json;charset=UTF-8") req.Header.Set("Origin", "https://fanyi.caiyunapp.com") req.Header.Set("Referer", "https://fanyi.caiyunapp.com/") req.Header.Set("Sec-Fetch-Dest", "empty") req.Header.Set("Sec-Fetch-Mode", "cors") req.Header.Set("Sec-Fetch-Site", "cross-site") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39") req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi") req.Header.Set("app-name", "xy") req.Header.Set("os-type", "web") req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Microsoft Edge";v="101"`) req.Header.Set("sec-ch-ua-mobile", "?0") req.Header.Set("sec-ch-ua-platform", `"Windows"`) resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() bodyText, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } var dictResponse DictResponse err = json.Unmarshal(bodyText, &dictResponse) if err != nil { log.Fatal(err) } fmt.Printf("%#v\n", dictResponse) } -
打印结果——选择打印需要阶段
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" ) type DictRequest struct { TransType string `json:"trans_type"` Source string `json:"source"` UserID string `json:"user_id"` } type DictResponse struct { Rc int `json:"rc"` Wiki Wiki `json:"wiki"` Dictionary Dictionary `json:"dictionary"` } type Description struct { Source string `json:"source"` Target interface{} `json:"target"` } type Item struct { Source string `json:"source"` Target string `json:"target"` } type Wiki struct { KnownInLaguages int `json:"known_in_laguages"` Description Description `json:"description"` ID string `json:"id"` Item Item `json:"item"` ImageURL string `json:"image_url"` IsSubject string `json:"is_subject"` Sitelink string `json:"sitelink"` } type Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } type Dictionary struct { Prons Prons `json:"prons"` Explanations []string `json:"explanations"` Synonym []interface{} `json:"synonym"` Antonym []interface{} `json:"antonym"` WqxExample []interface{} `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface{} `json:"related"` Source string `json:"source"` } func query(word string) { client := &http.Client{} request := DictRequest{TransType: "en2zh", Source: word} buf, err := json.Marshal(request) if err != nil { log.Fatal(err) } var data = bytes.NewReader(buf) req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data) if err != nil { log.Fatal(err) } req.Header.Set("Accept", "application/json, text/plain, */*") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") req.Header.Set("Connection", "keep-alive") req.Header.Set("Content-Type", "application/json;charset=UTF-8") req.Header.Set("Origin", "https://fanyi.caiyunapp.com") req.Header.Set("Referer", "https://fanyi.caiyunapp.com/") req.Header.Set("Sec-Fetch-Dest", "empty") req.Header.Set("Sec-Fetch-Mode", "cors") req.Header.Set("Sec-Fetch-Site", "cross-site") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39") req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi") req.Header.Set("app-name", "xy") req.Header.Set("os-type", "web") req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Microsoft Edge";v="101"`) req.Header.Set("sec-ch-ua-mobile", "?0") req.Header.Set("sec-ch-ua-platform", `"Windows"`) resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() bodyText, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } if resp.StatusCode != 200 { log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText)) } var dictResponse DictResponse err = json.Unmarshal(bodyText, &dictResponse) if err != nil { log.Fatal(err) } fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs) for _, item := range dictResponse.Dictionary.Explanations { fmt.Println(item) } } func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, `usage: simpleDict WORD example: simpleDict hello `) os.Exit(1) } word := os.Args[1] query(word) } 但非常遗憾的是,自己电脑 没有curl这个指令,所以需要在服务器上运行,不然一直出现

浙公网安备 33010602011771号