Load config with godotenv
Signed-off-by: Izuru Yakumo <yakumo.izuru@chaotic.ninja> git-svn-id: file:///srv/svn/repo/suwako/trunk@21 0b558ee1-521d-8b46-a41b-40029c97c055
This commit is contained in:
parent
106c12ccff
commit
17952ccae7
@ -9,8 +9,10 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"marisa.chaotic.ninja/suwako"
|
||||
"os"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"marisa.chaotic.ninja/suwako"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -23,40 +25,43 @@ var (
|
||||
type Translate struct {
|
||||
Output string `json:"translated_text"`
|
||||
}
|
||||
func init() {
|
||||
func loadCfg() {
|
||||
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(&input, "i", "", "Enter the text to be translated")
|
||||
flag.StringVar(&target, "t", "en", "Set the language to translate to")
|
||||
flag.StringVar(&target, "t", "", "Set the language to translate to")
|
||||
|
||||
flag.Usage = func() {
|
||||
fmt.Printf("usage: suwako -f [lang] -i [text] -t [lang]\nversion: %v\n", suwako.FullVersion())
|
||||
}
|
||||
}
|
||||
func main() {
|
||||
|
||||
home, err := os.UserHomeDir()
|
||||
sanityCheck(err)
|
||||
conf := home + "/.suwako/suwako.conf"
|
||||
err = godotenv.Load(conf)
|
||||
sanityCheck(err)
|
||||
|
||||
engine = os.Getenv("SUWAKO_ENGINE")
|
||||
instance = os.Getenv("SUWAKO_INSTANCE")
|
||||
|
||||
flag.Parse()
|
||||
}
|
||||
func check() {
|
||||
if len(input) == 0 || len(target) == 0 {
|
||||
log.Fatal("Either there is no input or there is no target language")
|
||||
}
|
||||
}
|
||||
func main() {
|
||||
loadCfg()
|
||||
check()
|
||||
|
||||
if len(engine) == 0 || len(instance) == 0 {
|
||||
log.Println("SUWAKO_ENGINE and/or SUWAKO_INSTANCE are unset")
|
||||
log.Println("Defaulting to simplytranslate.org with engine 'google'")
|
||||
engine = "google"
|
||||
instance = "https://simplytranslate.org"
|
||||
}
|
||||
if len(input) == 0 {
|
||||
log.Fatal("Missing input text.")
|
||||
}
|
||||
// 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)
|
||||
fmt.Printf("%v\n",translate.Output)
|
||||
|
2
go.mod
2
go.mod
@ -1,3 +1,5 @@
|
||||
module marisa.chaotic.ninja/suwako
|
||||
|
||||
go 1.18
|
||||
|
||||
require github.com/joho/godotenv v1.5.1
|
||||
|
Loading…
x
Reference in New Issue
Block a user