golang在线词典
- 前言
- 抓包
- 解析成go代码
- json转go结构体
- 输入看看效果
- 重点
前言
实现功能:输入一个英文单词,返回翻译及其英标。
这个项目非常简单,本文的主要目的是记录两个网站(curl语句转换成golang代码,json结构体转go结构体),留着以后直接用。
抓包
首先随便去一个翻译网站抓个包,这里我去的是彩云小译,然后随便输入一个单词,去找前端发送给后端的请求。
这里copy的内容是:
curl 'https://api.interpreter.caiyunai.com/v1/dict' \-H 'Connection: keep-alive' \-H 'os-version: ' \-H 'User-Agent: Mozilla/5.0 Linux; Android) AppleWebKit/537.36 KHTML, like Gecko) Chrome/88.0.4324.109 Safari/537.36 CrKey/1.54.248666' \-H 'app-name: xy' \-H 'Content-Type: application/json;charset=UTF-8' \-H 'Accept: application/json, text/plain, */*' \-H 'device-id: ' \-H 'os-type: web' \-H 'X-Authorization: token:qgemv4jr1y38jyq6vhvi' \-H 'Origin: https://fanyi.caiyunapp.com' \-H 'Sec-Fetch-Site: cross-site' \-H 'Sec-Fetch-Mode: cors' \-H 'Sec-Fetch-Dest: empty' \-H 'Referer: https://fanyi.caiyunapp.com/' \-H 'Accept-Language: zh-CN,zh;q=0.9' \--data-raw '{"trans_type":"en2zh","source":"good"}' \--compressed
解析成go代码
这个时候我们去这个网页:Convert curl commands to Python, JavaScript, PHP, R, Go, Rust, Elixir, Java, MATLAB, Dart, CFML, Ansible URI, Strest or JSON,将复制的内容粘贴到里面,就能得到go的代码了!
下面的代码都是网页解析curl自动生成的
package mainimport "fmt""io/ioutil""log""net/http""strings"
)func main) {client := &http.Client{}var data = strings.NewReader`{"trans_type":"en2zh","source":"good"}`)req, err := http.NewRequest"POST", "https://api.interpreter.caiyunai.com/v1/dict", data)if err != nil {log.Fatalerr)}req.Header.Set"Connection", "keep-alive")req.Header.Set"User-Agent", "Mozilla/5.0 Linux; Android) AppleWebKit/537.36 KHTML, like Gecko) Chrome/88.0.4324.109 Safari/537.36 CrKey/1.54.248666")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"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")resp, err := client.Doreq)if err != nil {log.Fatalerr)}defer resp.Body.Close)bodyText, err := ioutil.ReadAllresp.Body)if err != nil {log.Fatalerr)}fmt.Printf"%s\n", bodyText)
}
json转go结构体
运行程序后,我们发现返回的是json,我们需要将json反序列化到go的结构体中
{"rc":0,"wiki":{"known_in_laguages":63,"description":{"source":"tangible and intangible thing, except labor tied services, that satisfies human wants and provides utility","target":null},"id":"Q28877","item":{"source":"good","target":"\u5546\u54c1"},"image_url":"http:\/\/www.caiyunapp.com\/imgs\/link_default_img.png","is_subject":"true","sitelink":"https:\/\/www.caiyunapp.com\/read_mode\/?id=625b4b949c0120504d1e7b69"},"dictionary":{"prons":{"en-us":"[g\u028ad]","en":"[gud]"},"explanations":["a.\u597d\u7684;\u5584\u826f\u7684;\u5feb\u4e50\u7684;\u771f\u6b63\u7684;\u5bbd\u5927\u7684;\u6709\u76ca\u7684;\u8001\u7ec3\u7684;\u5e78\u798f\u7684;\u5fe0\u5b9e\u7684;\u4f18\u79c0\u7684;\u5b8c\u6574\u7684;\u5f7b\u5e95\u7684;\u4e30\u5bcc\u7684","n.\u5229\u76ca;\u597d\u5904;\u5584\u826f;\u597d\u4eba","ad.=well"],"synonym":["excellent","fine","nice","splendid","proper"],"antonym":["bad","wrong","evil","harmful","poor"],"wqx_example":[["to the good","\u6709\u5229,\u6709\u597d\u5904"],["good, bad and indifferent","\u597d\u7684,\u574f\u7684\u548c\u4e00\u822c\u7684"],["good innings","\u957f\u5bff"],["good and ...","\u5f88,\u9887;\u5b8c\u5168,\u5f7b\u5e95"],["do somebody's heart good","\u5bf9\u67d0\u4eba\u7684\u5fc3\u810f\u6709\u76ca,\u4f7f\u67d0\u4eba\u611f\u5230\u6109\u5feb"],["do somebody good","\u5bf9\u67d0\u4eba\u6709\u76ca"],["be good for","\u5bf9\u2026\u6709\u6548,\u9002\u5408,\u80dc\u4efb"],["be good at","\u5728\u2026\u65b9\u9762\u5b66\u5f97,\u505a\u5f97)\u597d;\u5584\u4e8e"],["as good as one's word","\u4fe1\u5b88\u8bfa\u8a00,\u503c\u5f97\u4fe1\u8d56"],["as good as","\u5b9e\u9645\u4e0a,\u51e0\u4e4e\u7b49\u4e8e"],["all well and good","\u4e5f\u597d,\u8fd8\u597d,\u5f88\u4e0d\u9519"],["a good","\u76f8\u5f53,\u8db3\u8db3"],["He is good at figures . ","\u4ed6\u5584\u4e8e\u8ba1\u7b97\u3002"]],"entry":"good","type":"word","related":[],"source":"wenquxing"}}
这么多的嵌套,手写岂不累死,这时就去第二个网页:JSON转Golang Struct
可以发现结构体已经生成好了,我们只需要将结构体赋值到代码中,进行反序列化即可
输入看看效果
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 {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"`
}func main) {client := &http.Client{}request := DictRequest{TransType: "en2zh", Source: "good"}buf, err := json.Marshalrequest)if err != nil {log.Fatalerr)}var data = bytes.NewReaderbuf)req, err := http.NewRequest"POST", "https://api.interpreter.caiyunai.com/v1/dict", data)if err != nil {log.Fatalerr)}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.Doreq)if err != nil {log.Fatalerr)}defer resp.Body.Close)bodyText, err := ioutil.ReadAllresp.Body)if err != nil {log.Fatalerr)}var dictResponse DictResponseerr = json.UnmarshalbodyText, &dictResponse)if err != nil {log.Fatalerr)}fmt.Printf"%+v\n", dictResponse)
}
{Rc:0 Wiki:{KnownInLaguages:63 Description:{Source:tangible and intangible thing, except labor tied services, that satisfies human wants and provides utility Target:<nil>} ID:Q28877 Item:{Source:good Target:商品} ImageURL:http://www.caiyunapp.com/imgs/link_default_img.png IsSubject:true Sitelink:https://www.caiyunapp.com/read_mode/?id=625b4b949c0120504d1e7b69} Dictionary:{Prons:{EnUs:[gʊd] En:[gud]} Explanations:[a.好的;善良的;快乐的;真正的;宽大的;有益的;老练的;幸福的;忠实的;优秀的;完整的;彻底的;丰富的 n.利益;好处;善良;好人 ad.=well] Synonym:[excellent fine nice splendid proper] Antonym:[bad wrong evil harmful poor] WqxExample:[[to the good 有利,有好处] [good, bad and indifferent 好的,坏的和一般的] [good innings 长寿] [good and ... 很,颇;完全,彻底] [do somebody's heart good 对某人的心脏有益,使某人感到愉快] [do somebody good 对某人有益] [be good for 对…有效,适合,胜任] [be good at 在…方面学得,做得)好;善于] [as good as one's word 信守诺言,值得信赖] [as good as 实际上,几乎等于] [all well and good 也好,还好,很不错] [a good 相当,足足] [He is good at figures . 他善于计算。]] Entry:good Type:word Related:[] Source:wenquxing}}
此时就输出好了,后续可以将单词替换成输入的单词,输入替换成翻译和英标即可。
重点
本文的重点在于crul转go代码和json转go结构体的两个工具的使用,我记得之前写一个项目的时候,手写es返回的json结构体,居然忘记了找工具去转换,心塞。