Go语言实例:命令行词典 | 青训营笔记

116 阅读5分钟
这是我参与「第五届青训营 」伴学笔记创作活动的第1天。

一、本课堂的目标

本节课主要是通过命令行调用词典实现对单词的查询。如下图所示。go run后面跟着两个参数,第一个参数是我们要运行的原代码,第二个参数则是需要查询的单词。

1.jpg

最终结果是单词的音标和它的注释。

二、本堂课的知识点

1.使用go语言发送http请求

2.如何解析json

3.代码生成

三、实践过程

打开chrome浏览器输入网址fanyi.caiyunapp.com/

在网页当中右键点击检查

image.png

打开浏览器的开发者工具

image.png

点击network以后,在左边文本框中输入good,右边会生成大量请求。

3.jpg

如果出现请求为空情况,请保持开发者工具打开的状态下刷新,再输入good。

image.png

找到name列下请求方法为post的dict请求(一般都是最下面的dict请求)。单击每个请求可以看里面的内容。

5.jpg

这里我们要将请求信息转化为请求代码,需要用到curlconverter.com/go/ 网页上的功能来快速生成go的请求代码

image.png

回到彩云翻译的网页,对我们刚刚选择的dict请求右键,选择copy,再选择Copy as cURL(bash)

6.jpg

在curlconverter网页当中编程语言选择go,并将刚刚复制的请求信息粘贴到红框处。下滑网页点击Copy to clipboard复制这段代码。

7.jpg

打开编译器,粘贴代码。此部分代码就是发送http请求并得到返回信息。

image.png

接下来通过json反序列化将收到的请求转化为结构体变量以方便我们获取需要的参数。

创建两个结构体,一个结构体作为发送请求时的字节流,另一个结构体是将用于网页返回的内容反序列化,方便读取。

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"`
}

其中DictResponse结构体获取方法如下

回到刚刚查看dict请求信息处,选择Preview,再对准第一行选择其中的Copy value,能够复制里面的内容。

9.jpg

打开网址oktools.net/json2go 选择左边目录栏中的JSON转Go Struct,将刚刚复制的内容粘贴到JSON底下的方框当中,选择转换-嵌套,将转换的结构体复制粘贴到代码当中。

103.jpg

修改代码当中的发送请求信息的data,通过将DictRequest结构体序列化以后,转化为byte数组,作为参数发送网页请求。

    client := &http.Client{}
    request := DictRequest{TransType: "en2zh", Source: "good"}
    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)
    }

在获取resp的内容后,判断是否返回一个错误请求。

    if resp.StatusCode != 200{
        log.Fatal("bad StatusCode:", resp.StatusCode)
    }

将转化为bodyText的网页信息,通过反序列化转化为结构体。这样我们能够通过结构体来快速访问我们需要的音标和注释。

    var response DictResponse
    err = json.Unmarshal(bodyText,&response)
    if err != nil{
            log.Fatal(err)
    }

    fmt.Println(word, "\nUK:", response.Dictionary.Prons.En, "\nUS:", response.Dictionary.Prons.EnUs)
    for _, item := range response.Dictionary.Explanations{
            fmt.Println(item)
    } 

最后将获取网页信息的主体改为query函数,以word作为变量输入想要翻译的单词,把"good"参数改为word变量。并重新写一个main主体,获取命令行信息,判断命令行是否有两个参数(也就是是否在go文件名后面是否输入单词),如果有,调用query函数,获取word的翻译信息。

func query(word string) {
    client := &http.Client{}
    request := DictRequest{TransType: "en2zh", Source: word}
}//只展示前三行修改信息

func main() {
    if len(os.Args)!=2{
        fmt.Println("Please Don't enter Empty")
        os.Exit(1)
    }
    word := os.Args[1]
    query(word)
}

五、总结

本堂课主要是学会使用网页请求的方式,并且学会了两个代码快速生成的便利工具。个人在学习该案例的过程中更多是在熟悉go语言的语法基础。

引用参考

【Golang·抓包】简单抓包代码生成工具的使用实例_godKnoows的博客-CSDN博客_golang抓包

完整代码

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 {
		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 query(word string) {
	client := &http.Client{}
	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")
	req.Header.Set("app-name", "xy")
	req.Header.Set("content-type", "application/json;charset=UTF-8")
	req.Header.Set("device-id", "")
	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="8", "Chromium";v="108", "Google Chrome";v="108"`)
	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/108.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)
	}
	if resp.StatusCode != 200{
		log.Fatal("bad StatusCode:", resp.StatusCode)
	}

	var response DictResponse
	err = json.Unmarshal(bodyText,&response)
	if err != nil{
		log.Fatal(err)
	}
	
	fmt.Println(word, "\nUK:", response.Dictionary.Prons.En, "\nUS:", response.Dictionary.Prons.EnUs)
	for _, item := range response.Dictionary.Explanations{
		fmt.Println(item)
	} 
 
}

func main() {
	if len(os.Args)!=2{
		fmt.Println("Please Don't enter Empty")
		os.Exit(1)
	}
	word := os.Args[1]
	query(word)
}