go 谷歌免费翻译
package main import ( "fmt" "io/ioutil" "net/http" "net/url" "strings" ) type fanyi struct { first string second string context string } func( f *fanyi) TranslateEn2Ch(ff *fanyi) (string, error) { url := fmt.Sprintf("https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s",ff.first,ff.second, url.QueryEscape(ff.context)) resp, err := http.Get(url) if err != nil { return "", err } defer resp.Body.Close() if err != nil { return "", err } bs, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } //返回的json反序列化比较麻烦, 直接字符串拆解 ss := string(bs) ss = strings.ReplaceAll(ss, "[", "") ss = strings.ReplaceAll(ss, "]", "") ss = strings.ReplaceAll(ss, "null,", "") ss = strings.Trim(ss, `"`) ps := strings.Split(ss, `","`) return ps[0], nil } func main() { var ff fanyi ff.first="zh-cn" ff.second="ja" ff.context="www.topgoer.com是个不错的go语言中文文档" str, err :=new(fanyi).TranslateEn2Ch(&ff) if err != nil { fmt.Println(err) } fmt.Println(str) }