source: code/trunk/main.go@ 10

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

rep: hard-coding api endpoint, change variable names to be less confusing, etc

File size: 1.7 KB
Line 
1// $TheSupernovaDuo: stcli,v 1.4.0 2023/03/13 08:14:55 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)
13
14var (
15 engine string
16 instance string
17 input string
18 source string
19 target string
20)
21type Translate struct {
22 Output string `json:"translated-text"`
23}
24func init() {
25 flag.StringVar(&engine, "e", "google", "Translation engine to use")
26 flag.StringVar(&source, "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://translate.bus-hit.me", "Instance to use)")
28 flag.StringVar(&input, "I", "", "Enter the text to be translated")
29 flag.StringVar(&target, "t", "en", "Set the language to translate to")
30}
31func main() {
32 // Begin flag parsing
33 flag.Parse()
34 // Check if there's any input, otherwise bail out.
35 if len(input) == 0 {
36 log.Fatal("Missing input.")
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 apiEndpoint = "/api/translate"
43 var queryURL = instance + apiEndpoint + "?engine=" + engine + "&from=" + source + "&to=" + target + "&text=" + encInput
44 // Begin the request and process the response
45 resp, err := http.Get(queryURL)
46 sanityCheck(err)
47 defer resp.Body.Close()
48 // JSON decoding
49 _ = json.NewDecoder(resp.Body).Decode(&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.