实战案例|青训营

100 阅读3分钟

Go语言的实战案例(下)

在线词典

  • 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("Connection", "keep-alive")
    	req.Header.Set("DNT", "1")
    	req.Header.Set("os-version", "")
    	req.Header.Set("sec-ch-ua-mobile", "?0")
    	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) 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("device-id", "")
    	req.Header.Set("os-type", "web")
    	req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
    	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")
    	req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
    	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, "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)
    }
    对每行代码写个讲解,并最后进行总结
    
    1. type DictRequest struct { ... }:定义了一个名为DictRequest的结构体,用于存储查询词典的请求参数。
    2. type DictResponse struct { ... }:定义了一个名为DictResponse的结构体,用于存储查询词典的响应数据。
    3. func query(word string) { ... }:定义了一个名为query的函数,用于发送查询词典的请求并解析响应数据。
    4. client := &http.Client{}:创建一个HTTP客户端。
    5. request := DictRequest{...}:构建一个DictRequest结构体实例,表示词典查询的请求参数。
    6. buf, err := json.Marshal(request):将请求参数结构体转换为JSON格式的字节流。
    7. var data = bytes.NewReader(buf):将JSON格式的字节流封装为bytes.Reader类型,准备作为请求体发送。
    8. req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data):创建一个POST请求,目标地址为api.interpreter.caiyunai.com/v1/dict
    9. req.Header.Set("Connection", "keep-alive")和其他类似的语句:设置请求头。
    10. resp, err := client.Do(req):发送HTTP请求并获取响应。
    11. defer resp.Body.Close():延迟关闭响应体,确保在函数结束后关闭。
    12. bodyText, err := ioutil.ReadAll(resp.Body):读取响应体的内容。
    13. err = json.Unmarshal(bodyText, &dictResponse):将响应体的内容解析为DictResponse结构体实例。
    14. fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)和其他类似的语句:打印查询结果。
    15. func main() { ... }:主函数,程序的入口。
    16. if len(os.Args) != 2 { ... }:判断命令行参数的个数是否为2,如果不是则打印使用说明并退出程序。
    17. word := os.Args[1]:获取命令行参数中的查询词。
    18. query(word):调用query函数进行词典查询。

总结

这是一个简单的词典查询功能。它使用HTTP客户端发送POST请求,将查询词作为请求参数发送给指定的API接口,并解析返回的JSON数据来获取查询结果。代码中展示了HTTP请求的发送、JSON数据的处理、结构体的定义和函数的封装。通过这个例子,可以帮助初学者了解如何使用Go进行网络请求和JSON数据处理。