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:
yakumo.izuru 2023-10-21 20:12:04 +00:00
parent 106c12ccff
commit 17952ccae7
3 changed files with 28 additions and 19 deletions

View File

@ -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)

2
go.mod
View File

@ -1,3 +1,5 @@
module marisa.chaotic.ninja/suwako
go 1.18
require github.com/joho/godotenv v1.5.1

2
go.sum
View File

@ -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=