aboutsummaryrefslogtreecommitdiffstats
path: root/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'main.go')
-rw-r--r--main.go126
1 files changed, 0 insertions, 126 deletions
diff --git a/main.go b/main.go
deleted file mode 100644
index 1da5f8e..0000000
--- a/main.go
+++ /dev/null
@@ -1,126 +0,0 @@
1package main
2
3import (
4 "flag"
5 "fmt"
6 "html/template"
7 "io"
8 "io/ioutil"
9 "log"
10 "net/http"
11 "net/url"
12 "strings"
13
14 "github.com/prologic/go-gopher"
15)
16
17var (
18 bind = flag.String("bind", ":80", "[int]:port to bind to")
19 uri = flag.String("uri", "127.0.0.1:70", "<host>:[port] to proxy to")
20
21 tpl *template.Template
22)
23
24type tplRow struct {
25 Link template.URL
26 Type string
27 Text string
28}
29
30func renderDirectory(w http.ResponseWriter, tpl *template.Template, hostport string, d gopher.Directory) error {
31 out := make([]tplRow, len(d))
32
33 for i, x := range d {
34 tr := tplRow{
35 Text: x.Description,
36 Type: x.Type.String(),
37 }
38
39 if x.Type == gopher.INFO {
40 out[i] = tr
41 continue
42 }
43
44 if strings.HasPrefix(x.Selector, "URL:") {
45 tr.Link = template.URL(x.Selector[4:])
46 } else {
47 var hostport string
48 if x.Port == 70 {
49 hostport = x.Host
50 } else {
51 hostport = fmt.Sprintf("%s:%d", x.Host, x.Port)
52 }
53 path := url.QueryEscape(x.Selector)
54 path = strings.Replace(path, "%2F", "/", -1)
55 tr.Link = template.URL(
56 fmt.Sprintf(
57 "/%s/%s%s",
58 hostport,
59 string(byte(x.Type)),
60 path,
61 ),
62 )
63 }
64
65 out[i] = tr
66 }
67
68 return tpl.Execute(w, struct {
69 Title string
70 Lines []tplRow
71 }{hostport, out})
72}
73
74func proxy(w http.ResponseWriter, req *http.Request) {
75 parts := strings.Split(strings.TrimPrefix(req.URL.Path, "/"), "/")
76 hostport := parts[0]
77 path := strings.Join(parts[1:], "/")
78
79 if len(hostport) == 0 {
80 http.Redirect(w, req, "/"+*uri, http.StatusFound)
81 return
82 }
83
84 uri, err := url.QueryUnescape(path)
85 if err != nil {
86 io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
87 return
88 }
89 res, err := gopher.Get(
90 fmt.Sprintf(
91 "gopher://%s/%s",
92 hostport,
93 uri,
94 ),
95 )
96 if err != nil {
97 io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
98 return
99 }
100
101 if res.Body != nil {
102 io.Copy(w, res.Body)
103 } else {
104 if err := renderDirectory(w, tpl, hostport, res.Dir); err != nil {
105 io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
106 return
107 }
108 }
109}
110
111func main() {
112 flag.Parse()
113
114 tpldata, err := ioutil.ReadFile(".template")
115 if err == nil {
116 tpltext = string(tpldata)
117 }
118
119 tpl, err = template.New("gophermenu").Parse(tpltext)
120 if err != nil {
121 log.Fatal(err)
122 }
123
124 http.HandleFunc("/", proxy)
125 log.Fatal(http.ListenAndServe(*bind, nil))
126}