source: code/trunk/main.go@ 6

Last change on this file since 6 was 6, checked in by koizumi.aoi, 2 years ago

Bugfix release: encode spaced words

Signed-off-by: Aoi K <koizumi.aoi@…>

File size: 1.8 KB
Line 
1// $KyokoNet: stcli-go,v 1.2 2022/12/13 22:13:00 akoizumi Exp
2// Command line client for SimplyTranslate, a privacy friendly frontend to Google Translate
3package main
4
5import (
6 "encoding/json"
7 "flag"
8 "fmt"
9 "io"
10 "log"
11 "net/http"
12 "net/url"
13 "os"
14)
15var (
16 engine string
17 from string
18 instance string
19 input string
20 to string
21)
22type Translate struct {
23 Output string `json:"translated-text"`
24}
25func init() {
26 flag.StringVar(&engine, "e", "google", "Translation engine to use (default: google)")
27 flag.StringVar(&from, "f", "auto", "Set the language to translate from. This can be skipped as it will autodetect the language you're translating from")
28 flag.StringVar(&instance, "i", "https://simplytranslate.org/api/translate/", "Instance to use (default: https://simplytranslate.org/api/translate/)")
29 flag.StringVar(&input, "I", "", "Enter the text to be translated")
30 flag.StringVar(&to, "t", "en", "Set the language to translate to (default: en)")
31}
32func main() {
33 // Begin flag parsing
34 flag.Parse()
35 // Check if any of those two variables is empty.
36 // It actually needs the two to have content.
37 if len(input) == 0 || len(to) == 0 {
38 log.Fatal("Missing either the text or the target language.")
39 os.Exit(1)
40 }
41 // Map a variable to the struct
42 var translate Translate
43 // Build the full URL to query
44 var encinput = url.PathEscape(input)
45 var queryURL = instance + "?engine=" + engine + "&from=" + from + "&to=" + to + "&text=" + encinput
46 // Begin the request and process the response
47 req, err := http.Get(queryURL)
48 sanityCheck(err)
49 defer req.Body.Close()
50 resp, err := io.ReadAll(req.Body)
51 _ = json.Unmarshal([]byte(resp), &translate)
52 sanityCheck(err)
53 // Pretty-print both the input and the output given.
54 fmt.Printf("Input: %v\n", input)
55 fmt.Printf("Output: %v\n",translate.Output)
56}
57func sanityCheck(err error) {
58 if err != nil {
59 log.Fatal(err)
60 }
61}
Note: See TracBrowser for help on using the repository browser.