From cc0c7e6eb5b27c3a263352ba40ce8ee5209272a2 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Wed, 11 Jan 2023 10:12:32 -0700 Subject: Simple client functionality and an example. --- examples/fetch/main.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/fetch/main.go (limited to 'examples') diff --git a/examples/fetch/main.go b/examples/fetch/main.go new file mode 100644 index 0000000..adfece4 --- /dev/null +++ b/examples/fetch/main.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/url" + "os" + "strings" + + "tildegit.org/tjp/gus/gemini" +) + +func main() { + if len(os.Args) < 2 { + fmt.Fprintf(os.Stderr, "usage: %s \n", os.Args[0]) + } + + certfile, keyfile := envConfig() + + // build a client + var client gemini.Client + if certfile != "" && keyfile != "" { + tlsConf, err := gemini.FileTLS(certfile, keyfile) + if err != nil { + log.Fatal(err) + } + client = gemini.NewClient(tlsConf) + } + + // parse the URL and build the request + request := &gemini.Request{URL: buildURL()} + + // fetch the response + response, err := client.RoundTrip(request) + if err != nil { + log.Fatal(err) + } + + if response.Status != gemini.StatusSuccess { + log.Fatalf("%d %s\n", response.Status, response.Meta) + } + + //io.Copy(os.Stdout, response) + buf, err := io.ReadAll(response) + fmt.Printf("response: %s\n", buf) +} + +func envConfig() (string, string) { + return os.Getenv("SERVER_CERTIFICATE"), os.Getenv("SERVER_PRIVATEKEY") +} + +func buildURL() *url.URL { + raw := os.Args[1] + if strings.HasPrefix(raw, "//") { + raw = "gemini:" + raw + } + + u, err := url.Parse(raw) + if err != nil { + log.Fatal(err) + } + + return u +} -- cgit v1.2.3