source: code/trunk/main.go@ 9

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

doc: target language is no longer required, put usage notes on readme.

File size: 1.8 KB
RevLine 
[9]1// $TheSupernovaDuo: stcli,v 1.3.1 2023/02/11 07:54:25 akoizumi Exp
[7]2// Command line client for SimplyTranslate, a privacy friendly frontend to other translation engines
[1]3package main
4
5import (
[3]6 "encoding/json"
7 "flag"
[1]8 "fmt"
[2]9 "log"
10 "net/http"
[6]11 "net/url"
[1]12)
13var (
[5]14 engine string
15 from string
16 instance string
17 input string
18 to string
[1]19)
[5]20type Translate struct {
21 Output string `json:"translated-text"`
[3]22}
[1]23func init() {
[5]24 flag.StringVar(&engine, "e", "google", "Translation engine to use (default: google)")
25 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")
26 flag.StringVar(&instance, "i", "https://simplytranslate.org/api/translate/", "Instance to use (default: https://simplytranslate.org/api/translate/)")
27 flag.StringVar(&input, "I", "", "Enter the text to be translated")
28 flag.StringVar(&to, "t", "en", "Set the language to translate to (default: en)")
[1]29}
30func main() {
[5]31 // Begin flag parsing
[1]32 flag.Parse()
[5]33 // Check if any of those two variables is empty.
34 // It actually needs the two to have content.
[9]35 if len(input) == 0 {
36 log.Fatal("Missing input.")
[2]37 }
[5]38 // Map a variable to the struct
39 var translate Translate
40 // Build the full URL to query
[6]41 var encinput = url.PathEscape(input)
42 var queryURL = instance + "?engine=" + engine + "&from=" + from + "&to=" + to + "&text=" + encinput
[5]43 // Begin the request and process the response
[8]44 resp, err := http.Get(queryURL)
[4]45 sanityCheck(err)
[8]46 defer resp.Body.Close()
[9]47 // JSON decoding
[8]48 _ = json.NewDecoder(resp.Body).Decode(&translate)
[4]49 sanityCheck(err)
[5]50 // Pretty-print both the input and the output given.
51 fmt.Printf("Input: %v\n", input)
52 fmt.Printf("Output: %v\n",translate.Output)
[1]53}
[4]54func sanityCheck(err error) {
55 if err != nil {
56 log.Fatal(err)
57 }
58}
Note: See TracBrowser for help on using the repository browser.