在线词典注释版| 青训营

89 阅读2分钟

关于在线词典的分析

本人刚刚看懂一点,有大佬说说gin是什么吗

用户可以在命令行里面查询一个单词。此程序能通过调用第三方的 API 查询到单词的翻译并打印出来。

在这个项目里面,我学习了如何用 go 语言来发送 HTTP 请求、解析 json,学习了如何使用代码生成来提高开发效率。用户可以在命令行里面查询一个单词。此程序能通过调用第三方的 API 查询到单词的翻译并打印出来。

在这个项目里面,我学习了如何用 go 语言来发送 HTTP 请求、解析 json,学习了如何使用代码生成来提高开发效率。

package main

import (
   "bytes"
   "encoding/json"
   "fmt"
   "io/ioutil"
   "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 main(){
   // 首先判断命令行参数
   // os.Args是一个string的切片,用来存储所有的命令行参数
   // args 第一个片 是文件路径
   // 第二个参数是, 用户输入的参数 例如 go run osdemo01.go 123
    if len(os.Args) != 2{
       // 打印错误
       // Fprintf() 根据 format格式说明符将内容格式化写入文件,返回内容是写入的字节与错误
       fmt.Fprintf(os.Stderr,`usage:simpleDict WORD example:simpleDict hello`)
       //  os.Exit() 函数终止程序
       //  退出程序且退出状态为3
       os.Exit(1)
    }
   word := os.Args[1]
   query(word)
}
func query(word string) {
   client := &http.Client{}
   // 将一个字符串转换为流
   //var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)
   // 创建一个 DictRequest 结构体
   request := DictRequest{TransType: "en2zh",Source: word}
   // 将结构体序列化
   buf , err := json.Marshal(request)
   // buf 是 []byte 类型,转化为流
   data := bytes.NewReader(buf)
   // 创建请求  三个参数 method 的 post ,url,data是一个流
   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,ja;q=0.7")
   req.Header.Set("app-name", "xy")
   req.Header.Set("content-type", "application/json;charset=UTF-8")
   req.Header.Set("device-id", "44fa7e1a11d1cb9b019a7b2ffe67511d")
   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", `"Google Chrome";v="113", "Chromium";v="113", "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/113.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 := ioutil.ReadAll(resp.Body)
   if err != nil {
      log.Fatal(err)
   }
   // 检查 response 状态码是否错误
   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,dictResponse.Dictionary.Prons.En,dictResponse.Dictionary.Prons.EnUs)
   for _,one := range dictResponse.Dictionary.Explanations{
      fmt.Println(one)
   }
}
`