suwako/main.go
koizumi.aoi 1d2d7d2020 How can you be in two places at once when you're not anywhere at all?
git-svn-id: file:///srv/svn/repo/suwako/trunk@8 0b558ee1-521d-8b46-a41b-40029c97c055
2022-12-17 16:57:12 +00:00

58 lines
1.8 KiB
Go

// $KyokoNet: stcli,v 1.3 2022/12/13 23:57:00 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
from string
instance string
input string
to string
)
type Translate struct {
Output string `json:"translated-text"`
}
func init() {
flag.StringVar(&engine, "e", "google", "Translation engine to use (default: google)")
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")
flag.StringVar(&instance, "i", "https://simplytranslate.org/api/translate/", "Instance to use (default: https://simplytranslate.org/api/translate/)")
flag.StringVar(&input, "I", "", "Enter the text to be translated")
flag.StringVar(&to, "t", "en", "Set the language to translate to (default: en)")
}
func main() {
// Begin flag parsing
flag.Parse()
// Check if any of those two variables is empty.
// It actually needs the two to have content.
if len(input) == 0 || len(to) == 0 {
log.Fatal("Missing either the text or the target language.")
}
// Map a variable to the struct
var translate Translate
// Build the full URL to query
var encinput = url.PathEscape(input)
var queryURL = instance + "?engine=" + engine + "&from=" + from + "&to=" + to + "&text=" + encinput
// Begin the request and process the response
resp, err := http.Get(queryURL)
sanityCheck(err)
defer resp.Body.Close()
_ = 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)
}
}