diff --git a/README.md b/README.md new file mode 100644 index 0000000..52c26ba --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# Install + +``` +go get github.com/turk/free-google-translate +``` + +# Example usage + +``` go +package main + +import ( + "fmt" + "github.com/turk/free-google-translate" + "net/http" +) + +func main() { + client := http.Client{} + t := translator.NewTranslator(&client) + result, _ := t.Translate("Hello!", "en", "ro") + fmt.Println(result) + // Output: "Salut!" +} +``` + +## Sponsors + +

+ + sponsors + +

diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b26c765 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/turk/free-google-translate + +go 1.18 \ No newline at end of file diff --git a/translator.go b/translator.go new file mode 100644 index 0000000..21f0602 --- /dev/null +++ b/translator.go @@ -0,0 +1,66 @@ +package translator + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +type Translator struct { + client *http.Client +} + +func NewTranslator(client *http.Client) Translator { + return Translator{client: client} +} + +func (t Translator) Translate(text, sourceLang, targetLang string) (string, error) { + var result []interface{} + var translated []string + + urlStr := fmt.Sprintf( + "https://translate.googleapis.com/translate_a/single?client=gtx&sl=%s&tl=%s&dt=t&q=%s", + sourceLang, + targetLang, + url.QueryEscape(text), + ) + + req, err := http.NewRequest(http.MethodGet, urlStr, nil) + res, err := t.client.Do(req) + + if err != nil { + return "err", errors.New("error getting translate.googleapis.com") + } + defer res.Body.Close() + + body, err := ioutil.ReadAll(res.Body) + + if err != nil { + return "err", errors.New("error reading response body") + } + + if res.StatusCode != 200 { + return "err", errors.New("translation failed") + } + + err = json.Unmarshal(body, &result) + if err != nil { + return "err", errors.New("error unmarshaling body") + } + + if len(result) > 0 { + data := result[0] + for _, slice := range data.([]interface{}) { + for _, translatedText := range slice.([]interface{}) { + translated = append(translated, fmt.Sprintf("%v", translatedText)) + break + } + } + return strings.Join(translated, ""), nil + } + return "err", errors.New("translation not found") +} diff --git a/translator_test.go b/translator_test.go new file mode 100644 index 0000000..0bc223a --- /dev/null +++ b/translator_test.go @@ -0,0 +1,20 @@ +package translator + +import ( + "net/http" + "testing" +) + +func TestTranslate(t *testing.T) { + client := http.Client{} + translator := NewTranslator(&client) + text := "Hello" + mdText := "Buna ziua" + + translated, _ := translator.Translate(text, "en", "ro") + if translated != mdText { + t.Logf("expected: %s", mdText) + t.Logf("given: %s", translated) + t.Fail() + } +}