-
Notifications
You must be signed in to change notification settings - Fork 0
/
yd.go
144 lines (110 loc) · 2.7 KB
/
yd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"encoding/json"
"fmt"
"os"
"io/ioutil"
"net/http"
"strings"
"net/url"
"crypto/md5"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
)
var (
//此处抄了https://github.com/TimothyYe/ydict的创意
Version = "0.1"
logo = `
__ __ ____
\ \ / / | _"\
\ V / /| | | |
U_|"|_uU| |_| |\
|_| |____/ u
.-,//|(_ |||_
\_) (__) (__)_)
YD V%s
https://github.com/littlespark/go-youdao
`
word, response, reqBody = "", "", ""
openApiUrl = "https://openapi.youdao.com/api"
appKey = "7ba6a5d54e032df3"
secertKey = "s5jxz5MWms4d10DHdQOoLp7xc5Y6MA3d"
)
func main() {
//.获取终端写入的字符
checkInput()
//. 显示执行进度条
s := spinner.New(spinner.CharSets[37], 30*time.Millisecond)
s.Color("green", "bold")
s.Start()
//.组装调用数据
build()
//.调用有道翻译http api并解析返回结果
httpPost()
//. 关闭执行进度条
s.Stop()
//.格式化返回内容,并美化输出 + 无翻译结果时输出错误
output()
}
func checkInput() string {
args := os.Args
if len(args) != 2 {
color.Cyan(logo, Version)
color.Cyan("Usage:")
color.Cyan("yd <word(s) to query> Query the word(s)")
os.Exit(0)
} else {
word = args[1]
}
return word
}
func build() {
//参数较少直接用string拼装
sign := appKey + word + "salt" + secertKey //md5(appKey+q+salt+应用密钥)
reqBody = "appKey=" + appKey + "&from=auto&to=auto" + "&q=" + url.QueryEscape(word) + "&salt=salt" + "&sign=" + encrypt(sign)
}
func encrypt(str string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}
func httpPost() {
resp, err := http.Post(openApiUrl, "application/x-www-form-urlencoded", strings.NewReader(reqBody))
if err != nil {
color.Blue("\r\n word '%s' not found", word)
os.Exit(0)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
color.Blue("\r\n word '%s' not found", word)
os.Exit(0)
}
response = string(body)
}
func output() {
var t TransResult
if err := json.Unmarshal([]byte(response), &t); err != nil {
color.Blue("\r\n word '%s' not found", word)
os.Exit(0)
}
if len(t.Basic.UsPhonetic) > 0 && len(t.Basic.UkPhonetic) > 0 {
color.Green("\r 英:[%v] 美:[%v]", t.Basic.UkPhonetic, t.Basic.UsPhonetic)
}
if len(t.Basic.Explains) > 0 {
fmt.Println("")
for _, v := range t.Basic.Explains {
color.Green("\r %v", v)
}
} else {
color.Red("\r\n word '%s' not found", word)
}
os.Exit(0)
}
//https://mholt.github.io/json-to-go/
type TransResult struct {
Basic struct {
UsPhonetic string `json:"us-phonetic"`
UkPhonetic string `json:"uk-phonetic"`
Explains []string `json:"explains"`
}
}