From 533bd4144ec26385bc263226913675e79f3258c4 Mon Sep 17 00:00:00 2001 From: aqua Date: Mon, 2 Aug 2021 20:44:44 +0300 Subject: gemcat can now do multiple requests at once - first do any requests specified in the -i (input) flag - then do any requests given as arguments --- main.go | 69 +++++++++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 23 deletions(-) diff --git a/main.go b/main.go index f5d241c..2079568 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "flag" "fmt" "log" @@ -12,6 +13,33 @@ func usage() { flag.PrintDefaults() } +func create_output(path string) (*os.File, error) { + if path == "" { + return os.Stdout, nil + } + return os.Create(path) +} + +func read_requests(path string) ([]string, error) { + if path == "" { + return nil, nil + } + + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var lines []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + return lines, scanner.Err() +} + func main() { flags := struct { host string @@ -31,36 +59,31 @@ func main() { flag.StringVar(&flags.input, "i", flags.input, "read urls from file") flag.StringVar(&flags.output, "o", flags.output, "write output to path") flag.Parse() - if flag.NArg() != 1 { - fmt.Printf("Error: Got %d arguments, expected 1\n", flag.NArg()) + + + requests, err := read_requests(flags.input) + if err != nil { + log.Panic(err) + } + requests = append(requests, flag.Args()...) + if len(requests) == 0 { flag.Usage() os.Exit(1) } - var conn *GeminiConn - var err error - - if flags.host != "" { - conn = NewGeminiConn(flags.host, flags.port) - } else { - conn, err = NewGeminiConnFromRequest(flag.Arg(0), flags.port) - if err != nil { - log.Fatalf("Error parsing hostname: %s\n", err.Error()) - } + output, err := create_output(flags.output) + if err != nil { + log.Fatal(err) } - log.Printf("connecting to: %s\n", conn.host) - - var output = os.Stdout - if flags.output != "" { - output, err = os.Create(flags.output) - if err != nil { - log.Fatalf("Error creating file: %s\n", err.Error()) + log.Printf("Got %d requests\n", len(requests)) + for _, request := range requests { + log.Println(request) + if conn, err := NewGeminiConnFromRequest(request, flags.port); err != nil { + log.Print(err) + } else if err := conn.Get(FormatRequest(request), output); err != nil { + log.Print(err) } } - err = conn.Get(FormatRequest(flag.Arg(0)), output) - if err != nil { - log.Fatalf("Error: %s\n", err.Error()) - } } -- cgit v1.2.1