[5] | 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
|
---|
[1] | 3 | package main
|
---|
| 4 |
|
---|
| 5 | import (
|
---|
[3] | 6 | "encoding/json"
|
---|
| 7 | "flag"
|
---|
[1] | 8 | "fmt"
|
---|
| 9 | "io"
|
---|
[2] | 10 | "log"
|
---|
| 11 | "net/http"
|
---|
[1] | 12 | "os"
|
---|
| 13 | )
|
---|
| 14 | var (
|
---|
[5] | 15 | engine string
|
---|
| 16 | from string
|
---|
| 17 | instance string
|
---|
| 18 | input string
|
---|
| 19 | to string
|
---|
[1] | 20 | )
|
---|
[5] | 21 | type Translate struct {
|
---|
| 22 | Output string `json:"translated-text"`
|
---|
[3] | 23 | }
|
---|
[1] | 24 | func init() {
|
---|
[5] | 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)")
|
---|
[1] | 30 | }
|
---|
| 31 | func main() {
|
---|
[5] | 32 | // Begin flag parsing
|
---|
[1] | 33 | flag.Parse()
|
---|
[5] | 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 {
|
---|
[4] | 37 | log.Fatal("Missing either the text or the target language.")
|
---|
[2] | 38 | os.Exit(1)
|
---|
| 39 | }
|
---|
[5] | 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
|
---|
[4] | 45 | req, err := http.Get(queryURL)
|
---|
| 46 | sanityCheck(err)
|
---|
[3] | 47 | defer req.Body.Close()
|
---|
[4] | 48 | resp, err := io.ReadAll(req.Body)
|
---|
[5] | 49 | _ = json.Unmarshal([]byte(resp), &translate)
|
---|
[4] | 50 | sanityCheck(err)
|
---|
[5] | 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)
|
---|
[1] | 54 | }
|
---|
[4] | 55 | func sanityCheck(err error) {
|
---|
| 56 | if err != nil {
|
---|
| 57 | log.Fatal(err)
|
---|
| 58 | }
|
---|
| 59 | }
|
---|