golang - youdao.dict Posted on 2017-11-13 | In Golang 查词小工具 获取翻译解释 获取发音(如果是英文) codepackage mainimport ( "encoding/json" "fmt" "io" "log" "net/http" "net/url" "os" "os/exec" "strings" "sync")// 翻译查询结果结构type translation struct { rawText string Translation []string `json:"translation"` Basic basicInfo `json:"basic"` ErrorCode int `json:"errorCode"`}// 内部结构type basicInfo struct { Explains []string `json:"explains"`}// 区分翻译和发音type sourceType struct { path string category int rawText string}func main() { // 传递翻译结构的ch ch := make(chan translation) var wg sync.WaitGroup // 获取所有需要请求的内容 for _, key := range translateURL(os.Args[1:]) { wg.Add(1) go func(key sourceType) { defer wg.Done() // 无论语音还是文字都要请求 resp, err := http.Get(key.path) if err != nil { fmt.Fprintf(os.Stderr, "fetch %v\n", err) os.Exit(1) } defer resp.Body.Close() // 文字翻译 if key.category == 0 { trans := translation{} err = json.NewDecoder(resp.Body).Decode(&trans) if err != nil { fmt.Fprintf(os.Stderr, "fetch %v\n", err) os.Exit(1) } if trans.ErrorCode != 0 { fmt.Fprintf(os.Stderr, "error code %v\n", trans.ErrorCode) os.Exit(1) } trans.rawText = key.rawText ch <- trans } // 发音类型处理 if key.category == 1 { out, err := os.Create("sample.mp3") if err != nil { // panic? } defer out.Close() // 存为文件 io.Copy(out, resp.Body) if err != nil { os.Exit(1) } // 用系统播放器播放 cmd := exec.Command("afplay", "sample.mp3") err = cmd.Start() if err != nil { log.Fatal(err) } fmt.Println("播放中...") err = cmd.Wait() } }(key) } go func() { wg.Wait() // 所有goroutines结束后结束ch close(ch) }() for item := range ch { // fmt.Println(item) explain := func() string { if len(item.Basic.Explains) > 0 { return strings.Join(item.Basic.Explains, "\n") } // 如果没有解释的内容 return "没有找到结果" }() fmt.Printf("%s - %s: \t \n%s", item.rawText, strings.Join(item.Translation, "|"), explain) fmt.Printf("\n \n") }}func translateURL(keys []string) (source []sourceType) { source = []sourceType{} for _, key := range keys { source = append(source, sourceType{path: "http://dict.youdao.com/speech?audio=" + url.QueryEscape(key), category: 1, rawText: key}) source = append(source, sourceType{path: "http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=json&version=1.1&q=" + url.QueryEscape(key), category: 0, rawText: key}) } return}