目的:熟悉go基础语法
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
type RequestParam struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
}
// 将json直接转成结构体
type ResponseNode 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 translate(word string) {
// 二、创建请求
// 要管理HTTP客户端的头域、重定向策略和其他设置,创建一个Client
// http.Client{Timeout: time.Second}可以自由设置请求过期时间
client := &http.Client{}
// 封装requestData
requestData := RequestParam{TransType: "en2zh", Source: word}
// 三、序列化请求
// 将结构体request序列化成JSON格式字符串
buf, err := json.Marshal(requestData)
if err != nil {
// fmt.Println("an error occured while json serialized,err->", err)
log.Fatal(err)
return
}
// 将序列化后的字符串转成字节数组
data := bytes.NewReader(buf)
// var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)
// 创建https请求
req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
// 判断是否出错
if err != nil {
log.Fatal(err)
}
// 设置请求头,注意应该用google的请求头,火狐的请求头有问题
req.Header.Set("Connection", "keep-alive")
req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"`)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) 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("os-type", "web")
req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
req.Header.Set("sec-ch-ua-platform", `"Windows"`)
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")
// 四、调用cliend.do发送请求,接受响应
resp, err := client.Do(req)
// 判断是否请求出错
if err != nil {
log.Fatal(err)
}
// 防止内存泄漏
defer resp.Body.Close()
// 五、读取响应体的数据
bodyText, err := ioutil.ReadAll(resp.Body)
// // 打印响应的body
// fmt.Printf("%s\n", bodyText)
// 判断是否出错
if err != nil {
log.Fatal(err)
}
if resp.StatusCode != 200 {
log.Fatal("bad StatusCode:", resp.StatusCode, "body:", string(bodyText))
}
// 六、解析响应的body
// 声明一个响应body节点
var responseData ResponseNode
// 反序列化bodyText
err = json.Unmarshal(bodyText, &responseData)
if err != nil {
log.Fatal("解析response出错,", err)
}
// fmt.Printf("%#v\n", responseData)
// fmt.Printf("%#v\n", responseData.Dictionary)
// fmt.Printf("%#v\n", responseData.Dictionary.Explanations)
// 打印翻译的音标
fmt.Println(word, "UK:", responseData.Dictionary.Prons.En, "US:", responseData.Dictionary.Prons.EnUs)
// 打印翻译结果
// 循环range,自带println函数
ans := responseData.Dictionary.Explanations
n := len(ans) //翻译的答案的个数
if n == 0 {
fmt.Println("ans is empty,please try again.")
return
}
for _, value := range ans {
println(value)
}
}
func main() {
// 一、动态读取用户输入的英文单词字符串
// fmt.Print("Please input a word to be translated: ")
// reader := bufio.NewReader(os.Stdin)
// word, err := reader.ReadString('\r')
// if err != nil {
// fmt.Println("an error occured while reading input.", err)
// return
// }
// word = strings.TrimSuffix(word, "\r")
// fmt.Printf("word:%s,len:%d\n", word, len(word))
// 改成命令行读取用户输入
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simleDict WORD
eg: simleDict hello
`)
os.Exit(1)
}
// 将命令行中的单词赋值给word
word := os.Args[1]
// 调用函数发送请求进行翻译
translate(word)
}
命令:
go run main.go
kevin
结果:
kevin UK: [ˈkivin] US: [ˈkεvɪn]
n.凯文(男子名)