commit bc2d17bbdcdab608b455830038c06378f79ac144
parent 0cba7275e3671519dc9bed9de1c28142ff0a2f55
Author: phoebos <ben@bvnf.space>
Date: Sat, 28 Aug 2021 17:53:13 +0100
add log() and die() for more concise error messages
Diffstat:
M | gemini.go | | | 43 | +++++++++++++++++++++++++++++-------------- |
1 file changed, 29 insertions(+), 14 deletions(-)
diff --git a/gemini.go b/gemini.go
@@ -6,19 +6,39 @@ import (
"flag"
"fmt"
"io/ioutil"
+ golog "log"
"net/url"
"os"
"strings"
)
+
+var (
+ v *bool
+)
+
+// log prints timestamped diagnosis messages to stderr if verbose output is turned on.
+func log(msg ...interface{}) {
+ if *v {
+ fmt.Fprint(os.Stderr, "\033[32m")
+ golog.Println(msg...)
+ fmt.Fprint(os.Stderr, "\033[m")
+ }
+}
+
+func die(msg ...interface{}) {
+ fmt.Fprintf(os.Stderr, "\033[31m%s\033[m\n", fmt.Sprint(msg...))
+ os.Exit(1)
+}
+
func main() {
port := flag.Int("p", 1965, "port number")
plain := flag.Bool("plain", false, "print raw header and response (no formatting)")
+ v = flag.Bool("v", false, "print more information to stderr")
flag.Parse()
// only accept one url
- if flag.NArg() > 1 {
- fmt.Fprintf(os.Stderr, "only give one url\n")
- os.Exit(1)
+ if flag.NArg() != 1 {
+ die("give one url")
}
u := flag.Args()[0]
@@ -29,14 +49,12 @@ func main() {
parsed, err := url.Parse(u)
if err != nil {
- fmt.Fprintf(os.Stderr, "error parsing url (%s): %s\n", u, err.Error())
- os.Exit(1)
+ die(fmt.Sprintf("error parsing url (%s): %s", u, err.Error()))
}
conn, err := tls.Dial("tcp", parsed.Host+fmt.Sprintf(":%d", *port), &tls.Config{InsecureSkipVerify: true})
if err != nil {
- fmt.Fprintf(os.Stderr, "tls error: %s\n", err.Error())
- os.Exit(1)
+ die("tls error: ", err)
}
defer conn.Close()
conn.Write([]byte(u + "\r\n"))
@@ -45,8 +63,7 @@ func main() {
if *plain {
resp, err := ioutil.ReadAll(bufio.NewReader(conn))
if err != nil {
- fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
- os.Exit(2)
+ die(err)
}
fmt.Println(string(resp))
os.Exit(0)
@@ -64,20 +81,18 @@ func main() {
// SUCCESS
case '3':
// REDIRECT
- fmt.Fprintf(os.Stderr, "redirecting to %s\n", statusline[3:])
+ log("redirecting to", statusline[3:])
case '6':
// CLIENT CERTIFICATE REQUIRED
default:
// reponse 4x or 5x
// FAILURE
- fmt.Fprintf(os.Stderr, "Error: %s\n", statusline)
- os.Exit(1)
+ die("error: ", statusline)
}
resp, err := ioutil.ReadAll(bufio.NewReader(conn))
if err != nil {
- fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
- os.Exit(1)
+ die("error: ", err.Error())
}
s := string(resp)
fmt.Println(*Prettify(&s))