Go 语言基础 - 基础语法 一、简介 1.1 什么是 Go 语言
高性能、高并发
语法简单、学习曲线平缓
丰富的标准库
完善的工具链
静态链接
快速编译
跨平台
垃圾回收
二、Go 语言入门 2.1 安装 Golang
下载 Go https://go.dev/
配置 Go 语言开发环境 VScode https://go.dev/ 或 Goland https://www.jetbrains.com/zh-cn/go/
2.2 基础语法 2.2.1 Hello World 1 2 3 4 5 6 7 8 9 package mainimport ( "fmt" ) func main () { fmt.Println("hello world" ) }
2.2.2 变量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package mainimport ( "fmt" "math" ) func main () { var a = "initial" var b, c int = 1 , 2 var d = true var e float64 f := float32 (e) g := a + "foo" fmt.Println(a, b, c, d, e, f) fmt.Println(g) const s string = "constant" const h = 500000000 const i = 3e20 / h fmt.Println(s, h, i, math.Sin(h), math.Sin(i)) }
2.2.3 循环 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package mainimport "fmt" func main () { i := 1 for { fmt.Println("loop" ) break } for j := 7 ; j < 9 ; j++ { fmt.Println(j) } for n := 0 ; n < 5 ; n++ { if n%2 == 0 { continue } fmt.Println(n) } for i <= 3 { fmt.Println(i) i = i + 1 } }
2.2.4 if 语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package mainimport "fmt" func main () { if 7 %2 == 0 { fmt.Println("7 is even" ) } else { fmt.Println("7 is odd" ) } if 8 %4 == 0 { fmt.Println("8 is divisible by 4" ) } if num := 9 ; num < 0 { fmt.Println(num, "is negative" ) } else if num < 10 { fmt.Println(num, "has 1 digit" ) } else { fmt.Println(num, "has multiple digits" ) } }
2.2.5 switch 语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package mainimport ( "fmt" "time" ) func main () { a := 2 switch a { case 1 : fmt.Println("one" ) case 2 : fmt.Println("two" ) case 3 : fmt.Println("three" ) case 4 , 5 : fmt.Println("four or five" ) default : fmt.Println("other" ) } t := time.Now() switch { case t.Hour() < 12 : fmt.Println("It's before noon" ) default : fmt.Println("It's after noon" ) } }
2.2.6 数组 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package mainimport "fmt" func main () { var a [5 ]int a[4 ] = 100 fmt.Println("get:" , a[2 ]) fmt.Println("get:" , a[4 ]) fmt.Println("len:" , len (a)) b := [5 ]int {1 , 2 , 3 , 4 , 5 } fmt.Println(b) var twoD [2 ][3 ]int for i := 0 ; i < 2 ; i++ { for j := 0 ; j < 3 ; j++ { twoD[i][j] = i + j } } fmt.Println("2d: " , twoD) }
2.2.7 切片 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package mainimport "fmt" func main () { s := make ([]string , 3 ) s[0 ] = "a" s[1 ] = "b" s[2 ] = "c" fmt.Println("get:" , s[2 ]) fmt.Println("len:" , len (s)) s = append (s, "d" ) s = append (s, "e" , "f" ) fmt.Println(s) c := make ([]string , len (s)) copy (c, s) fmt.Println(c) fmt.Println(s[2 :5 ]) fmt.Println(s[:5 ]) fmt.Println(s[2 :]) good := []string {"g" , "o" , "o" , "d" } fmt.Println(good) good = append (good, "d" ) fmt.Println(good) }
2.2.8 map 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package mainimport "fmt" func main () { m := make (map [string ]int ) m["one" ] = 1 m["two" ] = 2 fmt.Println(m) fmt.Println(len (m)) fmt.Println(m["one" ]) fmt.Println(m["unknow" ]) r, ok := m["unknow" ] fmt.Println(r, ok) delete (m, "one" ) m2 := map [string ]int {"one" : 1 , "two" : 2 } var m3 = map [string ]int {"one" : 1 , "two" : 2 } fmt.Println(m2, m3) }
2.2.9 range 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package mainimport "fmt" func main () { nums := []int {2 , 3 , 4 } sum := 0 for i, num := range nums { sum += num if num == 2 { fmt.Println("index:" , i, "num:" , num) } } fmt.Println(sum) m := map [string ]string {"a" : "A" , "b" : "B" } for k, v := range m { fmt.Println(k, v) } for k := range m { fmt.Println("key" , k) } }
2.2.10 函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package mainimport "fmt" func add (a int , b int ) int { return a + b } func add2 (a, b int ) int { return a + b } func exists (m map [string ]string , k string ) (v string , ok bool ) { v, ok = m[k] return v, ok } func main () { res := add(1 , 2 ) fmt.Println(res) v, ok := exists(map [string ]string {"a" : "A" }, "a" ) fmt.Println(v, ok) }
2.2.11 指针 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package mainimport "fmt" func add2 (n int ) { n += 2 } func add2ptr (n *int ) { *n += 2 } func main () { n := 5 add2(n) fmt.Println(n) add2ptr(&n) fmt.Println(n) }
2.2.12 结构体 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package mainimport "fmt" type user struct { name string password string } func main () { a := user{name: "wang" , password: "1024" } b := user{"wang" , "1024" } c := user{name: "wang" } c.password = "1024" var d user d.name = "wang" d.password = "1024" fmt.Println(a, b, c, d) fmt.Println(checkPassword(a, "haha" )) fmt.Println(checkPassword2(&a, "haha" )) } func checkPassword (u user, password string ) bool { return u.password == password } func checkPassword2 (u *user, password string ) bool { return u.password == password }
2.2.13 结构体方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package mainimport "fmt" type user struct { name string password string } func (u user) checkPassword(password string ) bool { return u.password == password } func (u *user) resetPassword(password string ) { u.password = password } func main () { a := user{name: "wang" , password: "1024" } a.resetPassword("2048" ) fmt.Println(a.checkPassword("2048" )) }
2.2.14 异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package mainimport ( "errors" "fmt" ) type user struct { name string password string } func findUser (users []user, name string ) (v *user, err error ) { for _, u := range users { if u.name == name { return &u, nil } } return nil , errors.New("not found" ) } func main () { u, err := findUser([]user{{"wang" , "1024" }}, "wang" ) if err != nil { fmt.Println(err) return } fmt.Println(u.name) if u, err := findUser([]user{{"wang" , "1024" }}, "li" ); err != nil { fmt.Println(err) return } else { fmt.Println(u.name) } }
2.2.15 字符串操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package mainimport ( "fmt" "strings" ) func main () { a := "hello" fmt.Println(strings.Contains(a, "ll" )) fmt.Println(strings.Count(a, "l" )) fmt.Println(strings.HasPrefix(a, "he" )) fmt.Println(strings.HasSuffix(a, "llo" )) fmt.Println(strings.Index(a, "ll" )) fmt.Println(strings.Join([]string {"he" , "llo" }, "-" )) fmt.Println(strings.Repeat(a, 2 )) fmt.Println(strings.Replace(a, "e" , "E" , -1 )) fmt.Println(strings.Split("a-b-c" , "-" )) fmt.Println(strings.ToLower(a)) fmt.Println(strings.ToUpper(a)) fmt.Println(len (a)) b := "你好" fmt.Println(len (b)) }
2.2.16 字符串格式化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package mainimport "fmt" type point struct { x, y int } func main () { s := "hello" n := 123 p := point{1 , 2 } fmt.Println(s, n) fmt.Println(p) fmt.Printf("s=%v\n" , s) fmt.Printf("n=%v\n" , n) fmt.Printf("p=%v\n" , p) fmt.Printf("p=%+v\n" , p) fmt.Printf("p=%#v\n" , p) f := 3.141592653 fmt.Println(f) fmt.Printf("%.2f\n" , f) }
2.2.17 JSON 处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package mainimport ( "encoding/json" "fmt" ) type userInfo struct { Name string Age int `json:"age"` Hobby []string } func main () { a := userInfo{Name: "wang" , Age: 18 , Hobby: []string {"Golang" , "TypeScript" }} buf, err := json.Marshal(a) if err != nil { panic (err) } fmt.Println(buf) fmt.Println(string (buf)) buf, err = json.MarshalIndent(a, "" , "\t" ) if err != nil { panic (err) } fmt.Println(string (buf)) var b userInfo err = json.Unmarshal(buf, &b) if err != nil { panic (err) } fmt.Printf("%#v\n" , b) }
2.2.18 时间处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package mainimport ( "fmt" "time" ) func main () { now := time.Now() fmt.Println(now) t := time.Date(2022 , 3 , 27 , 1 , 25 , 36 , 0 , time.UTC) t2 := time.Date(2022 , 3 , 27 , 2 , 30 , 36 , 0 , time.UTC) fmt.Println(t) fmt.Println(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()) fmt.Println(t.Format("2006-01-02 15:04:05" )) diff := t2.Sub(t) fmt.Println(diff) fmt.Println(diff.Minutes(), diff.Seconds()) t3, err := time.Parse("2006-01-02 15:04:05" , "2022-03-27 01:25:36" ) if err != nil { panic (err) } fmt.Println(t3 == t) fmt.Println(now.Unix()) }
2.2.19 数字解析 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package mainimport ( "fmt" "strconv" ) func main () { f, _ := strconv.ParseFloat("1.234" , 64 ) fmt.Println(f) n, _ := strconv.ParseInt("111" , 10 , 64 ) fmt.Println(n) n, _ = strconv.ParseInt("0x1000" , 0 , 64 ) fmt.Println(n) n2, _ := strconv.Atoi("123" ) fmt.Println(n2) n2, err := strconv.Atoi("AAA" ) fmt.Println(n2, err) }
2.2.20 进程信息 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package mainimport ( "fmt" "os" "os/exec" ) func main () { fmt.Println(os.Args) fmt.Println(os.Getenv("PATH" )) fmt.Println(os.Setenv("AA" , "BB" )) buf, err := exec.Command("grep" , "127.0.0.1" , "/etc/hosts" ).CombinedOutput() if err != nil { panic (err) } fmt.Println(string (buf)) }
三、实战 3.1 猜谜游戏
程序首先会生成一个介于 1 到 100 之间的随机整数, 然后提示玩家进行猜测
玩家每次输入一个数字, 程序就回告诉玩家这个猜测的值是高于还是低于随机数
猜对了就告诉玩家胜利并退出程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 package mainimport ( "bufio" "fmt" "math/rand" "os" "strconv" "strings" "time" ) func main () { maxNum := 100 rand.Seed(time.Now().UnixNano()) secretNumber := rand.Intn(maxNum) 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.Trim(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 } } }
3.2 在线词典
用户可以在命令行中查询一个单词, 我们通过调用第三方 API 查询单词的翻译并打印出来
使用 Go 来发送 HTTP 请求, 解析 JSON, 并使用代码生成来提高开发效率
3.2.1 抓包 先找到一个第三方 API
https://fanyi.caiyunapp.com
随便输入一个单词
点击翻译按钮
按 F12 进入开发者工具
在 Network 项中找到 All
左侧边栏从下向上找到最近的 dict ( 上面的都是之前请求的, 最下面的是最新的 )
检查请求头 Headers 中的请求形式应为 POST
Payload 中是一个 JSON 代码段
source 表示要翻译的词
trans_type 表示的是从英文翻译到中文
Preview 中显示的是这个词的翻译等
3.2.2 代码生成 右键 dict 一次选择 copy -> copy as cURL (bash) 复制所有请求头到一个空文件中
在这个网站中将拿到的 JSON 准换成 Go 语言
https://curlconverter.com/go/
将转换完成的代码粘贴回编译器是可以正常运行的, 可以看到返回了一大串 JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 package mainimport ( "fmt" "io/ioutil" "log" "net/http" "strings" ) func main () { client := &http.Client{} var data = strings.NewReader(`{"trans_type":"en2zh","source":"infer"}` ) req, err := http.NewRequest("POST" , "https://api.interpreter.caiyunai.com/v1/dict" , data) if err != nil { log.Fatal(err) } req.Header.Set("authority" , "api.interpreter.caiyunai.com" ) req.Header.Set("accept" , "application/json, text/plain, */*" ) req.Header.Set("accept-language" , "zh-CN,zh;q=0.9" ) req.Header.Set("app-name" , "xy" ) req.Header.Set("content-type" , "application/json;charset=UTF-8" ) req.Header.Set("device-id" , "" ) req.Header.Set("origin" , "https://fanyi.caiyunapp.com" ) req.Header.Set("os-type" , "web" ) req.Header.Set("os-version" , "" ) req.Header.Set("referer" , "https://fanyi.caiyunapp.com/" ) req.Header.Set("sec-ch-ua" , `"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"` ) req.Header.Set("sec-ch-ua-mobile" , "?0" ) req.Header.Set("sec-ch-ua-platform" , `"Windows"` ) 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/108.0.0.0 Safari/537.36" ) req.Header.Set("x-authorization" , "token:qgemv4jr1y38jyq6vhvi" ) 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) }
3.2.3 生成 request body go 语言中生成一段 JSON 常用的方式是先构造一个结构体, 结构体与 JSON 结构是一一对应的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 package mainimport ( "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("authority" , "api.interpreter.caiyunai.com" ) req.Header.Set("accept" , "application/json, text/plain, */*" ) req.Header.Set("accept-language" , "zh-CN,zh;q=0.9" ) req.Header.Set("app-name" , "xy" ) req.Header.Set("content-type" , "application/json;charset=UTF-8" ) req.Header.Set("device-id" , "" ) req.Header.Set("origin" , "https://fanyi.caiyunapp.com" ) req.Header.Set("os-type" , "web" ) req.Header.Set("os-version" , "" ) req.Header.Set("referer" , "https://fanyi.caiyunapp.com/" ) req.Header.Set("sec-ch-ua" , `"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"` ) req.Header.Set("sec-ch-ua-mobile" , "?0" ) req.Header.Set("sec-ch-ua-platform" , `"Windows"` ) 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/108.0.0.0 Safari/537.36" ) req.Header.Set("x-authorization" , "token:qgemv4jr1y38jyq6vhvi" ) 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) }
3.2.4 解析 response body go 语言是强语言类型, 不建议直接用 map 从 body 中取值
更常用的方法是和 request 一样写一个结构体, 然后把返回的 JSON 反序列化到结构体里面
https://oktools.net/json2go
将 Preview 中的 JSON 字符串复制到上述网站
右键 -> copy value
一定要是 rc 开头的整个这个东西, 不然之后生成的结构体会有问题
转换-展开 生成多个独立的结构体
转换-嵌套 生成一个单独的结构体
因为这个小项目不需要对数据进行单独的操作所以生成嵌套的即可
运行一下是这个效果, 已经可以将翻译的结果输出了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 package mainimport ( "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 struct { } `json:"wiki"` Dictionary struct { Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } `json:"prons"` Explanations []string `json:"explanations"` Synonym []string `json:"synonym"` Antonym []interface {} `json:"antonym"` WqxExample [][]string `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface {} `json:"related"` Source string `json:"source"` } `json:"dictionary"` } func main () { client := &http.Client{} request := DictRequest{TransType: "en2zh" , Source: "infer" } 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("authority" , "api.interpreter.caiyunai.com" ) req.Header.Set("accept" , "application/json, text/plain, */*" ) req.Header.Set("accept-language" , "zh-CN,zh;q=0.9" ) req.Header.Set("app-name" , "xy" ) req.Header.Set("content-type" , "application/json;charset=UTF-8" ) req.Header.Set("device-id" , "" ) req.Header.Set("origin" , "https://fanyi.caiyunapp.com" ) req.Header.Set("os-type" , "web" ) req.Header.Set("os-version" , "" ) req.Header.Set("referer" , "https://fanyi.caiyunapp.com/" ) req.Header.Set("sec-ch-ua" , `"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"` ) req.Header.Set("sec-ch-ua-mobile" , "?0" ) req.Header.Set("sec-ch-ua-platform" , `"Windows"` ) 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/108.0.0.0 Safari/537.36" ) req.Header.Set("x-authorization" , "token:qgemv4jr1y38jyq6vhvi" ) 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) }
3.2.5 打印结果 在一堆结果中截取我们想要的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 package mainimport ( "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 struct { } `json:"wiki"` Dictionary struct { Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } `json:"prons"` Explanations []string `json:"explanations"` Synonym []string `json:"synonym"` Antonym []interface {} `json:"antonym"` WqxExample [][]string `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface {} `json:"related"` Source string `json:"source"` } `json:"dictionary"` } func main () { client := &http.Client{} request := DictRequest{TransType: "en2zh" , Source: "infer" } 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("authority" , "api.interpreter.caiyunai.com" ) req.Header.Set("accept" , "application/json, text/plain, */*" ) req.Header.Set("accept-language" , "zh-CN,zh;q=0.9" ) req.Header.Set("app-name" , "xy" ) req.Header.Set("content-type" , "application/json;charset=UTF-8" ) req.Header.Set("device-id" , "" ) req.Header.Set("origin" , "https://fanyi.caiyunapp.com" ) req.Header.Set("os-type" , "web" ) req.Header.Set("os-version" , "" ) req.Header.Set("referer" , "https://fanyi.caiyunapp.com/" ) req.Header.Set("sec-ch-ua" , `"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"` ) req.Header.Set("sec-ch-ua-mobile" , "?0" ) req.Header.Set("sec-ch-ua-platform" , `"Windows"` ) 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/108.0.0.0 Safari/537.36" ) req.Header.Set("x-authorization" , "token:qgemv4jr1y38jyq6vhvi" ) 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) } var word string fmt.Println(word, "UK:" , dictResponse.Dictionary.Prons.En, "US:" , dictResponse.Dictionary.Prons.EnUs) for _, item := range dictResponse.Dictionary.Explanations { fmt.Println(item) } }
3.4.6 优化代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 package mainimport ( "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 struct { } `json:"wiki"` Dictionary struct { Prons struct { EnUs string `json:"en-us"` En string `json:"en"` } `json:"prons"` Explanations []string `json:"explanations"` Synonym []string `json:"synonym"` Antonym []interface {} `json:"antonym"` WqxExample [][]string `json:"wqx_example"` Entry string `json:"entry"` Type string `json:"type"` Related []interface {} `json:"related"` Source string `json:"source"` } `json:"dictionary"` } func query (word string ) { client := &http.Client{} request := DictRequest{TransType: "en2zh" , Source: "infer" } 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("authority" , "api.interpreter.caiyunai.com" ) req.Header.Set("accept" , "application/json, text/plain, */*" ) req.Header.Set("accept-language" , "zh-CN,zh;q=0.9" ) req.Header.Set("app-name" , "xy" ) req.Header.Set("content-type" , "application/json;charset=UTF-8" ) req.Header.Set("device-id" , "" ) req.Header.Set("origin" , "https://fanyi.caiyunapp.com" ) req.Header.Set("os-type" , "web" ) req.Header.Set("os-version" , "" ) req.Header.Set("referer" , "https://fanyi.caiyunapp.com/" ) req.Header.Set("sec-ch-ua" , `"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"` ) req.Header.Set("sec-ch-ua-mobile" , "?0" ) req.Header.Set("sec-ch-ua-platform" , `"Windows"` ) 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/108.0.0.0 Safari/537.36" ) req.Header.Set("x-authorization" , "token:qgemv4jr1y38jyq6vhvi" ) 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) }