这是我参与「第五届青训营」伴学笔记创作活动的第 14 天,今天继续对之前课程中的实战练习 —— 在线字典进行了简单的回顾,在这里进行小结
创建Request Body以及Response Body
先构建request的结构体
type DictRequest struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
}
其中,TransType是转换的类型,Source是我们需要翻译的单词
在创建结构体之后,我们先对结构体进行初始化,把TransType赋值为"en2zh",即英转中;对于Source则是我们输入的需要翻译的单词了
在初始化后,我们还需要对结构体进行序列化,转为json命令,即
var word string
fmt.Scanln(&word) //自己输入要查询的word
request := DictRequest{"en2zh", word}
buf, err := json.Marshal(request)
处理完请求,再利用网站进行代码转换,将预览中的json代码转换为response结构体
type DictResponse 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"`
}
在通过bodyText接收回复后,我们还需要将回复反序列化,转换为这个DictResponse来对回复加以利用
结果输出
在反序列化处理好response后,我们就可以根据结构体中的信息对我们需要的信息进行输出了
可以看到,英式英语音标的位置是dictResponse.Dictionary.Prons.En,美式英语音标的位置是dictResponse.Dictionary.Prons.EnUs,而单词的解释则是dictResponse.Dictionary.Explanations中,我们可以通过for range对dictResponse.Dictionary.Explanations进行遍历,将单词的意思进行输出。
fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
for _, item := range dictResponse.Dictionary.Explanations {
fmt.Println(item)
}
再将我们需要的信息进行输出后,这个小项目就算是完成了
总结
要实现这个在线词典,首先需要使用开发者工具,将请求复制为cUrl并转换为Go代码,这样我们的请求代码就有了;接着再将request以及response写成结构体,使用序列化和反序列化将json与结构体进行转换,在处理完回复的结果后,再将我们需要的信息进行输出即可。