Go语言实战1 | 青训营笔记

75 阅读3分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 4 天

编写在线词典

这部分涉及了API调用,代码自动生成等工作。首先需要获取翻译引擎的API,采用彩云小译,Google浏览器打开彩云小译,右键选择检查,在开发者工具找到network选项,在dict部分查找request是POST的请求,点击payload和preview,得到信息如下:

image-20230213151429483.png

对请求语句进行右键,选择:copy as CURL(bash),笔者在这里犯错,选择了copy as CURL(CMD)导致出现后续代码翻译信息不全的问题。

在网站 curlconverter.com 获得该URL翻译为Go语言的信息,URL语句为:

image-20230214180029177.png

注意,defer语句是用来关闭流,防止资源泄漏,在函数结束后,defer语句会从后往前触发。

考虑到在线词典的输入单词为变量,转换成结构体构造Json结构。

采用类似的方法,在彩云小译中,对dict指令,选中 response字符串,复制得到结果如下:

image-20230214180239646.png

打开oktools.net/json2go,进行代…

package main

import (
	"fmt"
	"io"
	"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 {
		KnownInLaguages int `json:"known_in_laguages"`
		Description struct {
			Source string `json:"source"`
			Target string `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 []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{}
	//var data = strings.NewReader(`{"trans_type":"en2zh","source":"test"}`)
	
	var request = DictRequest{TransType:"en2zh", Source:word}
	buf,err := json.Marshal(request)//序列化为byte数组
	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="99", "Google Chrome";v="109", "Chromium";v="109"`)
	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/109.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 := io.ReadAll(resp.Body)//读取响应
	if err != nil {
		log.Fatal(err)
	}
	//fmt.Printf("%s\n", bodyText)
	//防御式编程
	if resp.StatusCode != 200 {
		log.Fatal("bad StatusCode", resp.StatusCode, "Body", resp.BodyText)
	}
	//反序列化到dictResponse变量中
	var res DictResponse
	if err = json.UnMashal(bodyText, &res);err != nil{
		log.Fatal(err)
	}
	//打印全部语句 fmt.Println("%#v\n", res)
	fmt.Println(word, "UK:", res.Dictionary.Prons.Enus,"US: ", res.Dictionary.Prons.En)
	for _,i:=range res.Dictionary.Explanations {
		fmt.Println(i)
	}
}
func main(){
	if len(os.Args) != 2{
		fmt.Println(os.Stderr, `输入一个待查单词`)
		os.exit(1)
	}
	word := os.Args[1]
	query(word)
	
}

运行上述代码发生报错:

$ go run main.go your 
2023/02/13 16:33:33 bad StatusCode501Body{"message": "Unsupported trans_type"}
exit status 1

原因 是转换成Json的结构体编写错误,写作json:"trans_type"

如果输入参数格式正确,运行结果为:

image-20230214175610454.png

输入参数格式错误会提醒:

image-20230214175653891.png

出现网络问题:

image-20230214175727825.png

根据上述案例进行个人思考与发挥,尝试进行中文到日文的转换,因为没有出现dict指令,无法实现接口的利用。后续考虑采用其他翻译平台。