1 | // $KyokoNet: stcli-go,v 1.1 2022/12/13 10:07:00 akoizumi Exp
|
---|
2 | // Command line client for SimplyTranslate, a privacy friendly frontend to Google Translate
|
---|
3 | package main
|
---|
4 |
|
---|
5 | import (
|
---|
6 | "encoding/json"
|
---|
7 | "flag"
|
---|
8 | "fmt"
|
---|
9 | "io"
|
---|
10 | "log"
|
---|
11 | "net/http"
|
---|
12 | "os"
|
---|
13 | )
|
---|
14 | var (
|
---|
15 | engine string
|
---|
16 | from string
|
---|
17 | instance string
|
---|
18 | input string
|
---|
19 | to string
|
---|
20 | )
|
---|
21 | type Translate struct {
|
---|
22 | Output string `json:"translated-text"`
|
---|
23 | }
|
---|
24 | func 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 | }
|
---|
31 | func 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 | os.Exit(1)
|
---|
39 | }
|
---|
40 | // Map a variable to the struct
|
---|
41 | var translate Translate
|
---|
42 | // Build the full URL to query
|
---|
43 | var queryURL = instance + "?engine=" + engine + "&from=" + from + "&to=" + to + "&text=" + input
|
---|
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 | }
|
---|
55 | func sanityCheck(err error) {
|
---|
56 | if err != nil {
|
---|
57 | log.Fatal(err)
|
---|
58 | }
|
---|
59 | }
|
---|