这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记
课程代码链接
GitHub - wangkechun/go-by-example
课程PPT链接
Go 语言上手 - 基础语言.pptx - 飞书云文档 (feishu.cn)
Go语言基础
第一部分内容简略的讲述了Go语言的基础语法及部分使用情况,可以与Go语言圣经结合阅读
小项目实战
项目一:猜谜游戏
此项目对go语言的基础语法进行简单的使用,重点为随机数生成方法和控制结构的使用
项目二:简易在线词典
此项目利用彩云小译的查词api进行单词查询
首先获取HTTP请求的详细信息,复制请求的cURL(Bash)命令后,利用以下网站将相应的cURL命令转换为Go语言代码
Convert curl commands to code (curlconverter.com)
Go语言中通过创建相对应的结构体处理JSON数据,可以在下面的网站将JSON数据转换为Go中的结构体
JSON转Golang Struct - 在线工具 - OKTools
项目三:SOCK5代理
利用Go语言实现SOCK5协议进行SOCK5代理
课后习题
题目一:使用fmt.scanf()函数简化猜谜游戏
```
var guess int
_, err := fmt.Scanf("%d\n", &guess)
```
通过scanf直接读取输入的数字,简化了之前标准输入读取所需的字符串转换
题目二:修改在线词典,增加另一种翻译引擎的支持
使用有道智云AI (youdao.com)翻译引擎(没有音标,只有简单的翻译结果),按照之前彩云翻译的步骤重复即可,代码见题目三中
题目三:在上一步基础上修改代码实现并行请求两个翻译引擎来提高响应速度
此题需使用Goroutines和Channels来控制并发,可参考Goroutines和Channels · Go语言圣经 (studygolang.com)部分进行阅读
代码中设置了两个channel进行控制,get用于保证仅进行较快快的翻译引擎的输出,end用于保证在输出完成后主线程再退出
可以看见每次会选择较快的翻译引擎进行输出
具体代码:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
type DictReqCaiYun struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
UserID string `json:"user_id"`
}
type DictRespCaiYun struct {
Rc int `json:"rc"`
Wiki struct {
KnownInLaguages int `json:"known_in_laguages"`
Description struct {
Source string `json:"source"`
Target interface{} `json:"target"`
} `json:"description"`
ID string `json:"id"`
Item struct {
Source string `json:"source"`
Target string `json:"target"`
} `json:"item"`
ImageURL string `json:"image_url"`
IsSubject string `json:"is_subject"`
Sitelink string `json:"sitelink"`
} `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 []string `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"`
} // 用于彩云翻译
type DictRespYouDao struct {
ReturnPhrase []string `json:"returnPhrase"`
Query string `json:"query"`
ErrorCode string `json:"errorCode"`
L string `json:"l"`
TSpeakURL string `json:"tSpeakUrl"`
Web []Web `json:"web"`
RequestID string `json:"requestId"`
Translation []string `json:"translation"`
Dict Dict `json:"dict"`
Webdict Webdict `json:"webdict"`
Basic Basic `json:"basic"`
IsWord bool `json:"isWord"`
SpeakURL string `json:"speakUrl"`
}
type Web struct {
Value []string `json:"value"`
Key string `json:"key"`
}
type Dict struct {
URL string `json:"url"`
}
type Webdict struct {
URL string `json:"url"`
}
type Wf struct {
Name string `json:"name"`
Value string `json:"value"`
}
type Wfs struct {
Wf Wf `json:"wf"`
}
type Basic struct {
ExamType []string `json:"exam_type"`
UsPhonetic string `json:"us-phonetic"`
Phonetic string `json:"phonetic"`
UkPhonetic string `json:"uk-phonetic"`
Wfs []Wfs `json:"wfs"`
UkSpeech string `json:"uk-speech"`
Explains []string `json:"explains"`
UsSpeech string `json:"us-speech"`
} //用于有道翻译
func queryCaiYun(word string, get chan struct{}, close chan struct{}) {
client := &http.Client{}
request := DictReqCaiYun{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("Connection", "keep-alive")
req.Header.Set("DNT", "1")
req.Header.Set("os-version", "")
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
req.Header.Set("app-name", "xy")
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("device-id", "")
req.Header.Set("os-type", "web")
req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
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 DictRespCaiYun
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
get <- struct{}{}
fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
for _, item := range dictResponse.Dictionary.Explanations {
fmt.Println(item)
}
close <- struct{}{}
}
func queryYouDao(word string, get chan struct{}, close chan struct{}) {
client := &http.Client{}
var data = strings.NewReader(fmt.Sprintf(`q=%s&from=Auto&to=Auto`, word))
req, err := http.NewRequest("POST", "https://aidemo.youdao.com/trans", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("authority", "aidemo.youdao.com")
req.Header.Set("accept", "application/json, text/javascript, */*; q=0.01")
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,zh-TW;q=0.5")
req.Header.Set("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("origin", "https://ai.youdao.com")
req.Header.Set("referer", "https://ai.youdao.com/")
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", "?1")
req.Header.Set("sec-ch-ua-platform", `"Android"`)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Mobile Safari/537.36 Edg/101.0.1210.39")
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 DictRespYouDao
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
time.Sleep(80 * time.Millisecond) //不需要,由于有道引擎较快,添加阻塞时间以便于演示
get <- struct{}{}
fmt.Println(word)
for _, item := range dictResponse.Translation {
fmt.Println(item)
}
close <- struct{}{}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
`)
os.Exit(1)
}
word := os.Args[1]
get := make(chan struct{})
end := make(chan struct{}) //设置两个channel进行控制,get用于保证仅进行较快快的翻译引擎的输出,end用于保证在输出完成后主线程再退出
go queryCaiYun(word, get, end)
go queryYouDao(word, get, end)
<-get
<-end
}