Google translate api issue [SOLVED]

Hello,

it’s my first few days in the Go world…
I’m trying to use google’s free translate api… to translate strings (daaahh)

my code works from english to other languages (like russian)
but not the other way around. i can’t figure out what is the reason.

when i manually make a request to the api, the result downloads a txt file with correct response, i see the english and the russian strings

here’s a log from when i run my code with 2 attempts to translate:

//english to russian (works (in the browser) even though i see ??? instead of russian letters)

`URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=ru&dt=t&q=hello

`translation [[["???",“hello”,1]],“en”]

manual request to api returns [[["Здравствуйте","hello",,,1]],,"en"]

//russian to english: (doesn’t work)

`URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=Привет+мир

`translation [[["???µ?, ???","???µ?, ???",3]],“ru”]

in the browser it printed “РџСЂРёРІРμС, РјРёСЂ”

manual request to api returns [[["Hello World","Привет мир",,,1]],,"ru"]

bellow is a function that gets string to translate and the from and to language in ISO2
creates api url and makes the request.
manual requests in the browser return normal response and in both cases the response contains english and russian , so if it works 1 time, it should the second time as well…
so the only thing i can think of is that the api url which contains QueryEscape’d russian letters is not processed well like it does normally by the browser… without the encoding i have issue with spaces between words

package main

import (
	"github.com/gorilla/websocket"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	_ "unicode/utf8"
)

func main(){
     ... calling translateMessage and sending it back to front via socket..
}

func translateMessage(msg Message) string {

	apiurl := "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + msg.OriginalLang + "&tl=" + msg.Outlanguage + "&dt=t&q="

	escapedMessage := url.QueryEscape(msg.Message)

	log.Println("URL:", apiurl+escapedMessage)

	resp, err := http.Get(apiurl+escapedMessage)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	content := string(bytes)
	log.Println("translation", content)
	
	startIndex := strings.Index(content, "[[[\"")
	if startIndex == -1 {
		return msg.Message
	}
	startIndex += 4
	endIndex := strings.Index(content, "\",\"")
	if startIndex == -1 {
		return msg.Message
	}

	return content[startIndex:endIndex]
}

i also dont have a better idea of how to extract the translated string from the result, tried parsing it from json into slice [][][]string but that didn’t work… obviously

The response is not coming back in utf-8. This can be corrected by setting ie and oe in the query to UTF-8.

A full working example:

package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	log.SetFlags(log.Lshortfile)

	e2r := Message{
		OriginalLang: "en",
		Outlanguage:  "ru",
		Message:      "hello",
	}
	log.Println(translateMessage(e2r))

	r2e := Message{
		OriginalLang: "ru",
		Outlanguage:  "en",
		Message:      "Здравствуйте",
	}
	log.Println(translateMessage(r2e))
}

type Message struct {
	OriginalLang string
	Outlanguage  string
	Message      string
}

func translateMessage(msg Message) string {
	apiurl := "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + msg.OriginalLang + "&tl=" + msg.Outlanguage + "&dt=t&ie=UTF-8&oe=UTF-8&q="

	escapedMessage := url.QueryEscape(msg.Message)

	log.Println("URL:", apiurl+escapedMessage)

	resp, err := http.Get(apiurl + escapedMessage)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	content := string(bytes)
	log.Println("translation", content)

	startIndex := strings.Index(content, "[[[\"")
	if startIndex == -1 {
		return msg.Message
	}
	startIndex += 4
	endIndex := strings.Index(content, "\",\"")
	if startIndex == -1 {
		return msg.Message
	}

	return content[startIndex:endIndex]
}
1 Like

i thought it worked… but now it’s not returning anything at all (empty string)

that’s why my func returns back the original msg

https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=ru&ie=UTF-8&oe=UTF-8&q=hello

returns [,“en”]

not sure why the solution didn’t work yesterday… but i tried again and it works. thanks again

here’s my final code

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type Sentence struct {
	Trans string `json:"trans"`
	//Orig	    string `json:"orig"`
	//Backend   int    `json:"backend"`
}
type apiResponse struct {
	Sentences []Sentence `json:"sentences"`
	//Src      string      `json:"src"`
}

func TranslateMessage(msg Message) string {

	apiurl := "https://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&sl=" + msg.SourceLang + "&tl=" + msg.TargetLang + "&hl=ru&dt=t&dj=1&source=icon&tk=467103.467103&q="

	escapedMessage := url.QueryEscape(msg.Message)

	resp, err := http.Get(apiurl + escapedMessage)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	var r apiResponse
	err1 := json.Unmarshal(bytes, &r)
	if err1 != nil {
		log.Printf("err was %v", err1)
	}

	return r.Sentences[0].Trans
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.