source: code/trunk/main.go@ 11

Last change on this file since 11 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
RevLine 
[10]1// $TheSupernovaDuo: stcli,v 1.4.0 2023/03/13 08:14:55 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)
[10]13
[1]14var (
[5]15 engine string
16 instance string
17 input string
[10]18 source string
19 target string
[1]20)
[5]21type Translate struct {
22 Output string `json:"translated-text"`
[3]23}
[1]24func init() {
[10]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)")
[5]28 flag.StringVar(&input, "I", "", "Enter the text to be translated")
[10]29 flag.StringVar(&target, "t", "en", "Set the language to translate to")
[1]30}
31func main() {
[5]32 // Begin flag parsing
[1]33 flag.Parse()
[10]34 // Check if there's any input, otherwise bail out.
[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
[10]41 var encInput = url.PathEscape(input)
42 var apiEndpoint = "/api/translate"
43 var queryURL = instance + apiEndpoint + "?engine=" + engine + "&from=" + source + "&to=" + target + "&text=" + encInput
[5]44 // Begin the request and process the response
[8]45 resp, err := http.Get(queryURL)
[4]46 sanityCheck(err)
[8]47 defer resp.Body.Close()
[9]48 // JSON decoding
[8]49 _ = json.NewDecoder(resp.Body).Decode(&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]55func sanityCheck(err error) {
56 if err != nil {
57 log.Fatal(err)
58 }
59}
Note: See TracBrowser for help on using the repository browser.