suwako/main.go
koizumi.aoi f53dda01c9 rep: hard-coding api endpoint, change variable names to be less confusing, etc
git-svn-id: file:///srv/svn/repo/suwako/trunk@10 0b558ee1-521d-8b46-a41b-40029c97c055
2023-03-13 11:17:03 +00:00

60 lines
1.7 KiB
Go

// $TheSupernovaDuo: stcli,v 1.4.0 2023/03/13 08:14:55 akoizumi Exp
// Command line client for SimplyTranslate, a privacy friendly frontend to other translation engines
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/url"
)
var (
engine string
instance string
input string
source string
target string
)
type Translate struct {
Output string `json:"translated-text"`
}
func init() {
flag.StringVar(&engine, "e", "google", "Translation engine to use")
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")
flag.StringVar(&instance, "i", "https://translate.bus-hit.me", "Instance to use)")
flag.StringVar(&input, "I", "", "Enter the text to be translated")
flag.StringVar(&target, "t", "en", "Set the language to translate to")
}
func main() {
// Begin flag parsing
flag.Parse()
// Check if there's any input, otherwise bail out.
if len(input) == 0 {
log.Fatal("Missing input.")
}
// Map a variable to the struct
var translate Translate
// Build the full URL to query
var encInput = url.PathEscape(input)
var apiEndpoint = "/api/translate"
var queryURL = instance + apiEndpoint + "?engine=" + engine + "&from=" + source + "&to=" + target + "&text=" + encInput
// Begin the request and process the response
resp, err := http.Get(queryURL)
sanityCheck(err)
defer resp.Body.Close()
// JSON decoding
_ = json.NewDecoder(resp.Body).Decode(&translate)
sanityCheck(err)
// Pretty-print both the input and the output given.
fmt.Printf("Input: %v\n", input)
fmt.Printf("Output: %v\n",translate.Output)
}
func sanityCheck(err error) {
if err != nil {
log.Fatal(err)
}
}