go字典代码| 青训营笔记

125 阅读2分钟
这是Go实战案例里面的字典案例。
首先在彩云小译的网址中随便输入一个单词进行翻译,然后在控制台的网络选项中找到dict,同时请求为post的选项。
复制其cURL(cmd)格式。然后去[Convert curl commands to Go (curlconverter.com)](https://curlconverter.com/go/)网页粘贴复制的内容,将其转化为go代码,到本地编译。
到了这一步,我们已经成功了一半了。但是这只是我们的输入,我们还需要处理输入。
这个时候回到彩云小译的控制台网络选项中找到post请求的dict页面去复制其预览内容,粘贴至[JSON转Golang Struct - 在线工具 - OKTools](https://oktools.net/json2go)页面
将复制的内容粘贴到网址中,网页会帮我们生成对应go语言的struct结构体,这时候我们将结构体复制到我们的本地代码中。然后我们通过客户端执行go run "代码位置" "单词" 这样我们就可以实现dict查询了。
代码以及相应注释如下:


```package main
import (
   "bytes"
   "encoding/json"
   "fmt"
   "io"
   "log"
   "net/http"
   "os"
)
//用于存储数据,第一个为格式,第二个为单词
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 {
   } `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{}
   request := DictRequest{TransType: "en2zh", Source: word}
   buf, err2 := json.Marshal(request)
   if err2 != nil {
      log.Fatal(err2)
   }
   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", "82f9d613df16793de69d9120dadc7ebd")
   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", `"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"`)
   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/107.0.0.0 Safari/537.36 Edg/107.0.1418.35")
   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)
   }
   //保证其code的返回值是200 便于我们了解是是否是请求访问的问题,如果不是200就将结果输出
   //防止最后的结果为空
   if resp.StatusCode != 200 {
      log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
   }
   var dictResponse DictResponse
   err = json.Unmarshal(bodyText, &dictResponse)
   if err != nil {
      log.Fatal(err)
   }
   fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
   //循环将结果输出
   for _, item := range dictResponse.Dictionary.Explanations {
      fmt.Println(item)
   }
}
func main() {
   if len(os.Args) != 2 {
      fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
      `)
      os.Exit(1)
   }
   word := os.Args[1]
   query(word)
 }