aboutsummaryrefslogtreecommitdiffstats
path: root/main.go
blob: 6815b0bd76a7521140760f415393e8ca7d9b184f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main

import (
	"flag"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/prologic/go-gopher"
)

var (
	bind = flag.String("bind", ":80", "[int]:port to bind to")
	host = flag.String("host", "localhost", "host to proxy to")
	port = flag.Int("port", 70, "port to proxy to")
)

type tplRow struct {
	Link template.URL
	Type string
	Text string
}

func renderDirectory(w http.ResponseWriter, tpl *template.Template, d gopher.Directory) error {
	out := make([]tplRow, len(d))

	for i, x := range d {
		tr := tplRow{
			Text: x.Description,
			Type: x.Type.String(),
		}

		if x.Type == gopher.INFO {
			out[i] = tr
			continue
		}

		if strings.HasPrefix(x.Selector, "URL:") {
			tr.Link = template.URL(x.Selector[4:])
		} else {
			tr.Link = template.URL(
				fmt.Sprintf(
					"%s%s", string(byte(x.Type)), x.Selector,
				),
			)
		}

		out[i] = tr
	}

	return tpl.Execute(w, struct {
		Title string
		Lines []tplRow
	}{"XXX", out})
}

func proxy(w http.ResponseWriter, req *http.Request) {
	path := strings.TrimPrefix(req.URL.Path, "/")

	res, err := gopher.Get(fmt.Sprintf("gopher://%s:%d/%s", *host, *port, path))
	if err != nil {
		io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
		return
	}

	if res.Body != nil {
		io.Copy(w, res.Body)
	} else {
		if err := renderDirectory(w, tpl, res.Dir); err != nil {
			io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
			return
		}
	}
}

var tpl *template.Template

func main() {
	flag.Parse()

	tpldata, err := ioutil.ReadFile(".template")
	if err == nil {
		tpltext = string(tpldata)
	}

	tpl, err = template.New("gophermenu").Parse(tpltext)
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", proxy)
	log.Fatal(http.ListenAndServe(*bind, nil))
}