From 629956103b945e1596bab5c5dea163e849a8bf73 Mon Sep 17 00:00:00 2001
From: tjpcc <tjp@ctrl-c.club>
Date: Mon, 30 Oct 2023 11:06:49 -0600
Subject: [sw-fetch] send error outputs to stderr

fixes #14
---
 tools/sw-fetch/main.go | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)

diff --git a/tools/sw-fetch/main.go b/tools/sw-fetch/main.go
index cf37e50..8591fe2 100644
--- a/tools/sw-fetch/main.go
+++ b/tools/sw-fetch/main.go
@@ -5,11 +5,13 @@ import (
 	"crypto/tls"
 	"fmt"
 	"io"
+	"net/http"
 	"net/url"
 	"os"
 
 	"tildegit.org/tjp/sliderule"
 	"tildegit.org/tjp/sliderule/gemini"
+	"tildegit.org/tjp/sliderule/spartan"
 )
 
 const usage = `Resource fetcher for the small web.
@@ -53,7 +55,10 @@ func main() {
 		_ = conf.output.Close()
 	}()
 
-	_, _ = io.Copy(conf.output, response.Body)
+	success := printResponse(response, conf)
+	if !success {
+		os.Exit(1)
+	}
 }
 
 type config struct {
@@ -160,3 +165,34 @@ func stdinContents() (*io.LimitedReader, error) {
 		N: int64(len(contents)),
 	}, nil
 }
+
+func printResponse(response *sliderule.Response, conf config) bool {
+	success := true
+
+	switch conf.url.Scheme {
+	case "http", "https":
+		switch int(response.Status) / 100 {
+		case 4, 5:
+			fmt.Fprintf(os.Stderr, "http %d: %s\n", response.Status, http.StatusText(int(response.Status)))
+			success = false
+		}
+	case "gemini": //, "titan"
+		switch gemini.ResponseCategoryForStatus(response.Status) {
+		case gemini.ResponseCategoryTemporaryFailure, gemini.ResponseCategoryPermanentFailure, gemini.ResponseCategoryCertificateRequired:
+			fmt.Fprintf(os.Stderr, "gemini %d: %s\n", response.Status, response.Meta.(string))
+			success = false
+		}
+	case "spartan":
+		switch response.Status {
+		case spartan.StatusClientError, spartan.StatusServerError:
+			fmt.Fprintf(os.Stderr, "spartan %d: %s\n", response.Status, response.Meta.(string))
+			success = false
+		}
+	}
+
+	if _, err := io.Copy(conf.output, response.Body); err != nil {
+		fail(err.Error())
+	}
+
+	return success
+}
-- 
cgit v1.2.3