Writing a command line translation tool with Go language

Posted by – November 14, 2009

Go is a new language coming from Google, it isn’t fully object oriented as Java, or completely dynamic typed as Python, Go is in the middle of both worlds, it aims to be clean, fast to compile, safe and fun.

I wrote a small program where I can call the google translator service on the web to translate a text, and to be honest, its a very simple task, I wrote this tool in less than 5 hours without any previous experience with Go.

The entire program code can be checked below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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() {
    //Command line parser setup, defining command line flags
    flag.StringVar(&sourceLang, "s", "", "source language");
    flag.StringVar(&destLang, "d", "", "destination language");
    flag.StringVar(&text, "text", "", "text to be translated");
}

func main() {  
    //Parsing command line flags
    flag.Parse();
   
    //If no command line flags has been passed, print program usage
    if flag.NFlag() == 0 {
        Usage();
    }
   
    //Checking if all command line flags has been passed to the program
    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);
    }

    //Printing a status message to the user
    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);
   
    //Sending a request to google translator service
    response, _, _ := http.Get(requestString);

    //Checking server response
    if response.StatusCode == 200 {
        var array []byte;
        //Reading server response
        array, _ = io.ReadAll(response.Body);
        if array != nil {
            val, ok, _ := json.StringToJson(string(array));
            if ok {
                //Printing translated text to stdout
                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.");
    }
}

Please save the file above as itranslate.go and then you can compile the program by running:

$6g itranslate.go

And link with:

$6l -o itranslate itranslate.6

To run the program you my type the following command on terminal window:

itranslate --s "en" --d "it" --text "hello"
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>