底层逻辑
1.获取第三方api实时翻译\
在一个工具网站,例如翻译软件中打开浏览器控制台,使用network工具监测网络请求
找到我们需要的请求头复制成curl命令(我们需要通过这个名利的格式在代码生成器中生成go语言版本的http请求)
生成go语言代码 Convert curl commands to code (curlconverter.com)
运行之后我们就得到了一串json字符串,通同名结构体的操作实现json的序列化和反序列化
反序列化得到的输出一样可以通过代码生成器生成一个同名结构体方便我们输出
json转go-struct:JSON转Golang Struct - 在线工具 - OKTools 整理逻辑封装函数,最后写好main函数即可
2.发送http请求,解析json,同时使用代码生成工具提高开发效率
3.处理结果
重要步骤和包含知识
1.curl是什么
2.json是什么
3.方便测试的代码
代码块
//调用第三方api实时翻译
//发送http请求,解析json,如何使用代码生成提高开发效率
//打开在线翻译软件通过浏览器控制台的network工具获取POST请求(dict请求)
//复制请求的cURL到终端得到cURL代码,再将得到的cURL代码复制到快速转码的软件转换成go语言代码快速生成网络请求搭建代码
//注意黏贴到终端的
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
//构造一个同名首字母大写的结构体,通过json.Mashal()将请求序列化,转换成byte数组
type dictRequest struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
}
//通过代码生成,将序列化得到的json转成go-struct,同名大写就可以使用unmashal方法对json进行反序列化操作
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 []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 query(word string) {
client := &http.Client{}
// var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)
//序列化
request := dictRequest{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("authority", "api.interpreter.caiyunai.com")
req.Header.Set("accept", "application/json, text/plain, */*")
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")
req.Header.Set("app-name", "xy")
req.Header.Set("content-type", "application/json;charset=UTF-8")
req.Header.Set("device-id", "beb03841f392cc35aa95b970ed892a3f")
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", "Microsoft Edge";v="115", "Chromium";v="115"`)
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/115.0.0.0 Safari/537.36 Edg/115.0.1901.183")
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)
}
//得到的response不一定正确,比如url出错就会出现404报错,为了方便排查问题
if resp.StatusCode != 200 {
log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
}
// fmt.Printf("%s\n", bodyText) 得到json串
var dictResponse dictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err) //exit(1)并且输出错误信息
}
fmt.Printf(dictResponse.Dictionary.Entry, "US:", dictResponse.Dictionary.Prons.En, "UK:", dictResponse.Dictionary.Prons.EnUs)
fmt.Println('\n')
for _, item := range dictResponse.Dictionary.Explanations {
fmt.Println(item, '\n')
}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: shell_Dict WORD
example: shell_Dict hello
`)
os.Exit(1)
}
word := os.Args[1]
query(word)
}