source: code/trunk/main.go@ 8

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

How can you be in two places at once when you're not anywhere at all?

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