[新会话] @卷心菜,以下是转换后的Go语言代码:
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
const (
// 百度翻译API,需要自己申请appid和apikey
appID = ""
apiKey = ""
baseURL = "https://api.fanyi.baidu.com/api/trans/vip/translate"
// coscmd的路径
coscmdPath = "/usr/local/bin/coscmd"
// 存放图片的目录
cosBasePath = "blog/article_img/"
// cos的加速域名 /结尾
baseURLPrefix = "https://example.com/"
)
func main() {
if len(os.Args) <= 1 {
fmt.Println("Please provide the text to translate.")
return
}
text := strings.TrimSpace(os.Args[1])
text = strings.ReplaceAll(text, " ", "")
salt := fmt.Sprintf("%d", time.Now().Unix())
sign := md5.Sum([]byte(appID + text + salt + apiKey))
query := fmt.Sprintf("%s?q=%s&from=zh&to=en&appid=%s&salt=%s&sign=%s",
baseURL, text, appID, salt, hex.EncodeToString(sign[:]))
resp, err := http.Get(query)
if err != nil {
fmt.Printf("Failed to get translation for %s: %v", text, err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response body for %s: %v", text, err)
return
}
var dst string
fmt.Sscanf(string(body), `{"error_code":0,"error_msg":"SUCCESS","from":"zh","to":"en","trans_result":[{"src":"%s","dst":"%s"}]}`,
&text, &dst)
dir := strings.ToLower(strings.ReplaceAll(dst, " ", "-"))
var filenames []string
for _, arg := range os.Args[1:] {
if arg == os.Args[1] {
continue
}
absPath, err := filepath.Abs(arg)
if err != nil {
fmt.Printf("Failed to get absolute path for %s: %v", arg, err)
continue
}
if err := uploadToCos(absPath, filepath.Join(cosBasePath, dir)); err != nil {
fmt.Printf("Failed to upload %s: %v\n", arg, err)
continue
}
ext := filepath.Ext(arg)
filename := fmt.Sprintf("%s%s%s", baseURLPrefix, cosBasePath, filepath.Join(dir, strings.TrimSuffix(filepath.Base(absPath), ext)+ext))
filenames = append(filenames, filename)
}
fmt.Println("Upload Success:")
for _, name := range filenames {
fmt.Println(name)
}
}
func uploadToCos(localPath string, remoteDir string) error {
cmd := fmt.Sprintf("%s upload %s %s --force", coscmdPath, localPath, remoteDir)
if output, err := execShellCommand(cmd); err != nil {
return fmt.Errorf("%s: %v", output, err)
}
return nil
}
func execShellCommand(cmd string) (string, error) {
resultBytes, err := execShellCommandBytes(cmd)
if err != nil {
return "", err
}
return strings.TrimSpace(string(resultBytes)), nil
}
func execShellCommandBytes(cmd string) ([]byte, error) {
command