diff --git a/README.md b/README.md index e28c0cb..209b880 100755 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ## 安装 ```bash -go get github.com/UlinoyaPed/BaiduTranslate@v1.1 +go get github.com/UlinoyaPed/BaiduTranslate@v1.0.2 ``` ## 使用 @@ -110,7 +110,7 @@ en 错误码:54000,错误信息:PARAM_FROM_TO_OR_Q_EMPTY ``` -## 受支持的翻译语言 +## 受支持的翻译语言(部分) **(源语言语种不确定时可设置为 auto,目标语言语种不可设置为 auto)** diff --git a/demos/FileTranslate/FileTranslate.go b/demos/FileTranslate/FileTranslate.go index 46058b8..794b7a2 100644 --- a/demos/FileTranslate/FileTranslate.go +++ b/demos/FileTranslate/FileTranslate.go @@ -3,49 +3,29 @@ package main import ( "bufio" "fmt" - "io" + "io/ioutil" "log" "os" - "path" "strings" "time" - "translate/BaiduTranslate" - - "github.com/dablelv/go-huge-util/file" + "github.com/UlinoyaPed/BaiduTranslate" ) func init() { now := time.Now() - file := "./" + now.Format("2006-01-02") + ".log" // 使用2006年1月2号15点04分 + file := "./" + now.Format("2006-01-02") + ".log" logFile, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755) if err != nil { - log.Println(err.Error()) + log.Fatal(err) } - log.SetOutput(logFile) // 将文件设置为log输出的文件 + log.SetOutput(logFile) log.SetPrefix("[Translate]") log.SetFlags(log.LstdFlags | log.Lshortfile) - - return -} - -func FindFile(dirname string, format string) ([]string, error) { - names, err := file.GetDirAllEntryPaths(dirname, true) - if err != nil { - log.Println(err.Error()) - } - var result []string - ext := "" - for i := 0; i < len(names); i++ { - ext = path.Ext(names[i]) - if ext == format { - result[i] = names[i] - } - } - return result, err } func main() { + // 打印欢迎消息 s := `如果您第一次使用,请在本目录下创建profile.txt,并填入您的AppID和SecretKey 一行一个,不加前后缀! 请填入正确的AppID和SecretKey,否则输出为空! @@ -55,59 +35,50 @@ jXXEOXyXXXfXXXXXsXXX ` fmt.Println(s) - deploy, err := os.OpenFile("profile.txt", os.O_RDONLY|os.O_CREATE, 0755) + // 读取配置文件中的AppID和SecretKey + deployData, err := ioutil.ReadFile("profile.txt") if err != nil { - log.Println(err.Error()) + log.Fatal(err) } - - d := bufio.NewReader(deploy) - appID, _ := d.ReadString('\n') - appID = strings.TrimSpace(appID) - secretKey, _ := d.ReadString('\n') - secretKey = strings.TrimSpace(secretKey) + deployLines := strings.Split(string(deployData), "\n") + appID := strings.TrimSpace(deployLines[0]) + secretKey := strings.TrimSpace(deployLines[1]) btr := BaiduTranslate.BaiduInfo{AppID: appID, SecretKey: secretKey} - in, err := os.OpenFile("input.txt", os.O_RDONLY|os.O_CREATE, 0755) + // 读取输入文件内容 + inputData, err := ioutil.ReadFile("input.txt") if err != nil { - log.Println(err.Error()) + log.Fatal(err) } - // 创建 Reader - r := bufio.NewReader(in) + inputLines := strings.Split(string(inputData), "\n") - file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) + // 打开输出文件 + outputFile, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) if err != nil { - fmt.Println(err.Error()) + log.Fatal(err) } - defer file.Close() - writer := bufio.NewWriter(file) + defer outputFile.Close() + + writer := bufio.NewWriter(outputFile) - i := 0 n := 0 from := "en" to := "zh" - for { - line, ierr := r.ReadString('\n') - line = strings.TrimSpace(line) // 去掉字符串首尾空白字符 - if ierr != nil && ierr != io.EOF { - log.Println(err.Error()) - } - - i++ - + for i, line := range inputLines { + line = strings.TrimSpace(line) if line == "" { - log.Printf("第%d行是空行", i) + log.Printf("第%d行是空行", i+1) fmt.Println() - _, err = writer.WriteString("\n") if err != nil { - log.Println(err.Error()) + log.Fatal(err) } - } else { if n != 1 { + // 检测语言并切换翻译方向 lang := btr.Detect(line) if lang.Err() != nil { - log.Println(lang.Err().Error()) + log.Printf("第%d行出现错误,错误:%s", i+1, lang.Err().Error()) } else { fmt.Printf("语言:%s\n", lang.Lang) if lang.Lang == to { @@ -118,32 +89,26 @@ jXXEOXyXXXfXXXXXsXXX } } + // 进行翻译 result := btr.NormalTr(line, from, to) if result.Err() != nil { - log.Printf("第%d行出现错误,错误:%s", i, result.Err().Error()) + log.Printf("第%d行出现错误,错误:%s", i+1, result.Err().Error()) _, err = writer.WriteString("\n") } else { fmt.Printf("%s\n", result.Dst) - log.Printf("第%d行翻译完成!", i) - + log.Printf("第%d行翻译完成!", i+1) _, err = writer.WriteString(result.Dst + "\n") if err != nil { - log.Println(err.Error()) + log.Fatal(err) } } - } - - if ierr == io.EOF { - break - } - } fmt.Println("---翻译已完成,按回车键退出---") log.Println("---翻译已完成---") + // 刷新缓冲区并关闭写入器 writer.Flush() BaiduTranslate.Input() - return } diff --git a/demos/FileTranslate/go.mod b/demos/FileTranslate/go.mod new file mode 100644 index 0000000..4e8fdfe --- /dev/null +++ b/demos/FileTranslate/go.mod @@ -0,0 +1,14 @@ +module FileTranslate + +go 1.19 + +require ( + github.com/dablelv/cyan v0.0.54 + github.com/tidwall/gjson v1.17.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect +) + +require github.com/UlinoyaPed/BaiduTranslate v0.0.0 + +replace github.com/UlinoyaPed/BaiduTranslate => ../../ diff --git a/demos/FileTranslate/go.sum b/demos/FileTranslate/go.sum new file mode 100644 index 0000000..01a94f3 --- /dev/null +++ b/demos/FileTranslate/go.sum @@ -0,0 +1,8 @@ +github.com/dablelv/cyan v0.0.54 h1:LFMzt0gndYJFbSScw/kGeTvfVZkszds7HJDjKFu69Hk= +github.com/dablelv/cyan v0.0.54/go.mod h1:SyRS9eXKDIXKiTgQ3Qjs97FsMh2mPi9ndPRDkJqSR3g= +github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= +github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= diff --git a/demos/NormalTranslate/NormalTranslate.go b/demos/NormalTranslate/NormalTranslate.go index 6137554..5c6a9f3 100644 --- a/demos/NormalTranslate/NormalTranslate.go +++ b/demos/NormalTranslate/NormalTranslate.go @@ -6,7 +6,7 @@ import ( "os" "strings" - "translate/BaiduTranslate" + "github.com/UlinoyaPed/BaiduTranslate" ) func main() { diff --git a/demos/NormalTranslate/go.mod b/demos/NormalTranslate/go.mod new file mode 100644 index 0000000..f154020 --- /dev/null +++ b/demos/NormalTranslate/go.mod @@ -0,0 +1,13 @@ +module NormalTranslate + +go 1.19 + +require ( + github.com/tidwall/gjson v1.17.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect +) + +require github.com/UlinoyaPed/BaiduTranslate v0.0.0 + +replace github.com/UlinoyaPed/BaiduTranslate => ../../ diff --git a/demos/NormalTranslate/go.sum b/demos/NormalTranslate/go.sum new file mode 100644 index 0000000..2b213a0 --- /dev/null +++ b/demos/NormalTranslate/go.sum @@ -0,0 +1,6 @@ +github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= +github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3387848 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/UlinoyaPed/BaiduTranslate + +go 1.19 diff --git a/normal.go b/normal.go index 2fd01ae..3987f83 100644 --- a/normal.go +++ b/normal.go @@ -4,71 +4,88 @@ import ( "crypto/md5" "encoding/hex" "errors" + "fmt" "io/ioutil" - "log" "net/http" "net/url" + "time" "github.com/tidwall/gjson" ) +// NormalResult 包含翻译结果和错误信息的结构体 type NormalResult struct { - Dst string - - errCode string - errMsg string + Dst string // 翻译结果 + ErrCode string // 错误码 + ErrMsg string // 错误信息 } -func (BaiduInfo *BaiduInfo) NormalTr(Text string, From string, To string) NormalResult { - - //合并字符串,计算sign +// NormalTr 执行普通翻译的方法 +func (info *BaiduInfo) NormalTr(text, from, to string) NormalResult { + // 生成随机盐值 salt := Salt(10) - montage := BaiduInfo.AppID + Text + salt + BaiduInfo.SecretKey - ctx := md5.New() - ctx.Write([]byte(montage)) - sign := hex.EncodeToString(ctx.Sum(nil)) + // 构造待翻译的字符串,并计算签名 + sign := generateSign(info.AppID, text, salt, info.SecretKey) - // 传入需要翻译的语句 - urlstr := "http://fanyi-api.baidu.com/api/trans/vip/translate?q=" + url.QueryEscape(Text) + "&from=" + From + "&to=" + To + "&appid=" + BaiduInfo.AppID + "&salt=" + salt + "&sign=" + sign + // 构造请求URL + urlStr := "http://fanyi-api.baidu.com/api/trans/vip/translate?q=" + url.QueryEscape(text) + "&from=" + from + "&to=" + to + "&appid=" + info.AppID + "&salt=" + salt + "&sign=" + sign - // 发送GET请求 - resp, err := http.Get(urlstr) + // POST请求 + method := "POST" + // 5秒超时 + timeout := time.Duration(5 * time.Second) + client := &http.Client{ + Timeout: timeout, + } + req, err := http.NewRequest(method, urlStr, nil) if err != nil { - log.Println("HTTP GET出现错误!") + fmt.Println(err) + // return } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + // 发送请求 + res, err := client.Do(req) + if err != nil { + fmt.Println(err) + // return + } + defer res.Body.Close() - bodyJson := string(body) - var res NormalResult - res.errCode = gjson.Get(bodyJson, "error_code").String() - res.errMsg = gjson.Get(bodyJson, "error_msg").String() - if res.errCode == "" { - trans := gjson.Get(bodyJson, "trans_result").Array()[0] - res.Dst = trans.Get("dst").String() + // 解析返回数据 + body, err := ioutil.ReadAll(res.Body) + if err != nil { + fmt.Println(err) + // return } - return res + //fmt.Println(string(body)) + + bodyJSON := string(body) + var resp NormalResult + resp.ErrCode = gjson.Get(bodyJSON, "error_code").String() + resp.ErrMsg = gjson.Get(bodyJSON, "error_msg").String() + if resp.ErrCode == "" { + trans := gjson.Get(bodyJSON, "trans_result").Array()[0] + resp.Dst = trans.Get("dst").String() + } + return resp } -func (j NormalResult) Err() error { - if j.errCode != "" { - err := errors.New("通用翻译错误,错误码:" + j.errCode + ",错误信息:" + j.errMsg) +// Err 返回翻译错误信息 +func (result NormalResult) Err() error { + if result.ErrCode != "" { + err := errors.New("通用翻译错误,错误码:" + result.ErrCode + ",错误信息:" + result.ErrMsg) return err } else { return nil } } -/* -// json解析 - trans := gjson.Get(string(body), "trans_result").Array()[0] - result := trans.Get("dst").String() - errorCode := gjson.Get(string(body), "error_code").String() - errorMsg := gjson.Get(string(body), "error_msg").String() - if errorCode != "" { - err := errors.New("错误码:" + errorCode + ",错误信息:" + errorMsg) - return "", err - } else { - return result, nil - } -*/ +// generateSign 根据给定的参数生成签名 +func generateSign(appID, text, salt, secretKey string) string { + // 合并字符串,计算sign + montage := appID + text + salt + secretKey + hash := md5.New() + hash.Write([]byte(montage)) + sign := hex.EncodeToString(hash.Sum(nil)) + return sign +} diff --git a/test.go.off b/test.go.off new file mode 100644 index 0000000..6d002db --- /dev/null +++ b/test.go.off @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net/http" + "time" +) + +func main() { + + url := "https://fanyi-api.baidu.com/api/trans/vip/translate?q=hello&from=en&to=zh&appid=20220517001219044&salt=64143&sign=bd5a1af281e41f98b1739a0282ee00ce" + method := "POST" + + timeout := time.Duration(5 * time.Second) + client := &http.Client{ + Timeout: timeout, + } + req, err := http.NewRequest(method, url, nil) + + if err != nil { + fmt.Println(err) + return + } + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + req.Header.Add("Cookie", "BAIDUID=686D97BBF64B8829474597EA3006E5B8:FG=1") + + res, err := client.Do(req) + if err != nil { + fmt.Println(err) + return + } + defer res.Body.Close() + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(body)) +}