diff --git a/cmd/suwako/main.go b/cmd/suwako/main.go index f1ca55f..fa42019 100644 --- a/cmd/suwako/main.go +++ b/cmd/suwako/main.go @@ -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() - 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" + flag.Parse() +} +func check() { + if len(input) == 0 || len(target) == 0 { + log.Fatal("Either there is no input or there is no target language") } - if len(input) == 0 { - log.Fatal("Missing input text.") - } - // Map a variable to the struct +} +func main() { + loadCfg() + check() + 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) diff --git a/go.mod b/go.mod index 022ec39..5a8036c 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module marisa.chaotic.ninja/suwako go 1.18 + +require github.com/joho/godotenv v1.5.1 diff --git a/go.sum b/go.sum index e69de29..d61b19e 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=