source: code/trunk/main.go@ 7

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

Release v1.3:

  • Rename to stcli
  • Removed useless imports
  • Removed a no-op function call
  • Update README

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

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