Skip to content

Instantly share code, notes, and snippets.

@ararog ararog/itranslate.go
Created Sep 17, 2014

Embed
What would you like to do?
package main
import (
"json";
"flag";
"fmt";
"http";
"os";
"io";
)
var Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]);
flag.PrintDefaults();
os.Exit(1);
}
var sourceLang string;
var destLang string;
var text string;
func init() {
flag.StringVar(&sourceLang, "s", "", "source language");
flag.StringVar(&destLang, "d", "", "destination language");
flag.StringVar(&text, "text", "", "text to be translated");
}
func main() {
flag.Parse();
if flag.NFlag() == 0 {
Usage();
}
if len(sourceLang) == 0 {
fmt.Println("You must specify the source language!");
os.Exit(1);
}
else if len(destLang) == 0 {
fmt.Println("You must specify the destination language!");
os.Exit(1);
}
else if len(text) == 0 {
fmt.Println("You must provide the text to be translated!");
os.Exit(1);
}
fmt.Println(fmt.Sprintf("Translating %q from %s to %s", text, sourceLang, destLang));
var requestString string = fmt.Sprintf("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s%%7C%s", http.URLEscape(text), sourceLang, destLang);
response, _, _ := http.Get(requestString);
if response.StatusCode == 200 {
var array []byte;
array, _ = io.ReadAll(response.Body);
if array != nil {
val, ok, _ := json.StringToJson(string(array));
if ok {
var responseData json.Json = json.Walk(val, "responseData/translatedText");
fmt.Println(fmt.Sprintf("Result: %s", responseData.String()));
}
}
}
else {
fmt.Println("An error occured while calling google translator service.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.