青训营笔记:go语言实战案例——命令行字典 | 豆包MarsCode AI刷题

45 阅读5分钟

实践2:命令行翻译

1.打开彩云翻译

fanyi.caiyunapp.com/

  • 使用检查找到dict

dict.png

  • 点击复制

图片 2.png

2.生成请求:打开curl网址粘贴进去生成向彩云翻译发送POST的请求代码

curlconverter.com/go/

package main

import (
"fmt"
"io"
"log"
"net/http"
"strings"
)

func main() {
 client := &http.Client{}
 var data = strings.NewReader(`{"trans_type":"zh2en","source":"time"}`)
 req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("accept", "application/json, text/plain, */*")
req.Header.Set("accept-language", "zh")
req.Header.Set("app-name", "xiaoyi")
req.Header.Set("authorization", "Bearer")
req.Header.Set("content-type", "application/json;charset=UTF-8")
req.Header.Set("device-id", "e80716c3a237b76d72b6b4b6359d3a68")
req.Header.Set("origin", "https://fanyi.caiyunapp.com")
req.Header.Set("os-type", "web")
req.Header.Set("os-version", "")
req.Header.Set("priority", "u=1, i")
req.Header.Set("referer", "https://fanyi.caiyunapp.com/")
req.Header.Set("sec-ch-ua", `"Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"`)
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/130.0.0.0 Safari/537.36 Edg/130.0.0.0")
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)
}
fmt.Printf("%s\n", bodyText)
}

3.创建请求结构体,修改main函数请求代码

// 请求结构体
type DictRequest struct {
    TransType string `json:"trans_type"`
    Source    string `json:"source"`
    UserID    string `json:"user_id"`
}

    client := &http.Client{}
    //创建请求结构体,初始化字段
    request := DictRequest{TransType: "en2zh", Source: "good"}
    //序列化结构体为 JSON格式的字节切片[]byte
    buf, err := json.Marshal(request)
    if err != nil {
        log.Fatal(err)
    }
    //将字节切片 buf 转换为io.Reader

    var data = bytes.NewReader(buf)
    req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)

4.收集返回数据:使用代码生成网站生成返回数据的结构体

  • 打开网站dict的预览,复制返回数据 图片 3.png

oktools.iokde.com/json2go

  • 打开代码生成网站,粘贴返回数据,点击转换,得到返回数据结构体
type AutoGenerated 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 []interface{} `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"`
}

5.将返回的数据bodyText状态码检查再反序列化

    // 请求响应状态码检查
    if resp.StatusCode != 200 {
        log.Fatal("bad StatusCode:", resp.StatusCode)
    }

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

    // 打印所有返回结果
    fmt.Printf("%#v\n", dictResponse)
    //打印需要内容
    fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
    for _, item := range dictResponse.Dictionary.Explanations {
        fmt.Println(item)
    }

结果:

图片 4.png


知识点:

  defer resp.Body.Close()

  • resp.Body.Close() 主要用于确保在 HTTP 请求响应结束后,能够正确地关闭响应体(resp.Body)。它用于资源管理,避免因未关闭响应体而造成内存泄露或文件描述符浪费。
  • defer 语句用于延迟函数的执行,直到当前函数执行完毕后再执行。
  • 在 Go 中,当通过 http.Client 发起 HTTP 请求并获得响应时,响应体
  • resp.Body 是一个打开的流(通常是一个网络连接)。

for _, item := range dictResponse.Dictionary.Explanations

  • range 是 Go 语言中遍历各种数据结构(数组、切片、映射、字符串、通道等)的强大工具。它会返回索引(或键)和值,并且适用于不同的数据类型。如果只需要其中一个值,可以通过 _ 来忽略另一个值。 for index, value := range collection { // 使用 index 和 value}

完整代码:

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 {
        KnownInLanguages int `json:"known_in_languages"` // 拼写修正
        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 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)
}

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", "1.0.0") // 可以替换为空字符串
    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", "123456") // 可填充实际值
    req.Header.Set("os-type", "web")
    req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi") // 确保 Token 可用
    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 语句用于延迟函数的执行,直到当前函数执行完毕后再执行。
    defer resp.Body.Close()

    bodyText, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    // 请求响应状态码检查
    if resp.StatusCode != 200 {
        log.Fatal("bad StatusCode:", resp.StatusCode)
    }

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

    // 打印返回结果
    fmt.Printf("%#v\n", dictResponse)
    fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
    for _, item := range dictResponse.Dictionary.Explanations {
        fmt.Println(item)
    }
}

心得:

在青训营关于go的学习中由于我几乎没有接触过go语言,所以在实战视频课时学起来比较的吃力,不过好在有豆包ai可以让我在学习的过程中省去一些查资料的麻烦。当我有不懂的地方时可以直接把代码发过去,我问它关于此代码的go语言基础语法、知识点、用法和知识点相关的其他知识。例如:

image.png 总之ai让我在学习的过程中轻松了不少,省去了查资料看视频的时间,让我能更容易地保持注意力在学习上。