[6] | 1 | // $KyokoNet: stcli-go,v 1.2 2022/12/13 22:13:00 akoizumi Exp
|
---|
[5] | 2 | // Command line client for SimplyTranslate, a privacy friendly frontend to Google Translate
|
---|
[1] | 3 | package main
|
---|
| 4 |
|
---|
| 5 | import (
|
---|
[3] | 6 | "encoding/json"
|
---|
| 7 | "flag"
|
---|
[1] | 8 | "fmt"
|
---|
| 9 | "io"
|
---|
[2] | 10 | "log"
|
---|
| 11 | "net/http"
|
---|
[6] | 12 | "net/url"
|
---|
[1] | 13 | "os"
|
---|
| 14 | )
|
---|
| 15 | var (
|
---|
[5] | 16 | engine string
|
---|
| 17 | from string
|
---|
| 18 | instance string
|
---|
| 19 | input string
|
---|
| 20 | to string
|
---|
[1] | 21 | )
|
---|
[5] | 22 | type Translate struct {
|
---|
| 23 | Output string `json:"translated-text"`
|
---|
[3] | 24 | }
|
---|
[1] | 25 | func init() {
|
---|
[5] | 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)")
|
---|
[1] | 31 | }
|
---|
| 32 | func main() {
|
---|
[5] | 33 | // Begin flag parsing
|
---|
[1] | 34 | flag.Parse()
|
---|
[5] | 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 {
|
---|
[4] | 38 | log.Fatal("Missing either the text or the target language.")
|
---|
[2] | 39 | os.Exit(1)
|
---|
| 40 | }
|
---|
[5] | 41 | // Map a variable to the struct
|
---|
| 42 | var translate Translate
|
---|
| 43 | // Build the full URL to query
|
---|
[6] | 44 | var encinput = url.PathEscape(input)
|
---|
| 45 | var queryURL = instance + "?engine=" + engine + "&from=" + from + "&to=" + to + "&text=" + encinput
|
---|
[5] | 46 | // Begin the request and process the response
|
---|
[4] | 47 | req, err := http.Get(queryURL)
|
---|
| 48 | sanityCheck(err)
|
---|
[3] | 49 | defer req.Body.Close()
|
---|
[4] | 50 | resp, err := io.ReadAll(req.Body)
|
---|
[5] | 51 | _ = json.Unmarshal([]byte(resp), &translate)
|
---|
[4] | 52 | sanityCheck(err)
|
---|
[5] | 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)
|
---|
[1] | 56 | }
|
---|
[4] | 57 | func sanityCheck(err error) {
|
---|
| 58 | if err != nil {
|
---|
| 59 | log.Fatal(err)
|
---|
| 60 | }
|
---|
| 61 | }
|
---|