From 669492455bba0426fdb30dec650c94a8744b926b Mon Sep 17 00:00:00 2001 From: James Mills Date: Thu, 22 Sep 2016 12:51:46 +1000 Subject: Added templating support --- main.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++--------- template.go | 14 +++++++++++++ 2 files changed, 74 insertions(+), 10 deletions(-) create mode 100644 template.go diff --git a/main.go b/main.go index be625c6..6815b0b 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,9 @@ package main import ( "flag" "fmt" + "html/template" "io" + "io/ioutil" "log" "net/http" "strings" @@ -17,31 +19,79 @@ var ( port = flag.Int("port", 70, "port to proxy to") ) -func proxy(res http.ResponseWriter, req *http.Request) { +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, "/") - gr, err := gopher.Get(fmt.Sprintf("gopher://%s:%d/%s", *host, *port, path)) + res, err := gopher.Get(fmt.Sprintf("gopher://%s:%d/%s", *host, *port, path)) if err != nil { - io.WriteString(res, fmt.Sprintf("Error:
%s
", err)) + io.WriteString(w, fmt.Sprintf("Error:
%s
", err)) return } - if gr.Body != nil { - io.Copy(res, gr.Body) + if res.Body != nil { + io.Copy(w, res.Body) } else { - bytes, err := gr.Dir.ToText() - if err != nil { - io.WriteString(res, fmt.Sprintf("Error:
%s
", err)) + if err := renderDirectory(w, tpl, res.Dir); err != nil { + io.WriteString(w, fmt.Sprintf("Error:
%s
", err)) return } - - io.WriteString(res, string(bytes)) } } +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)) } diff --git a/template.go b/template.go new file mode 100644 index 0000000..7c13451 --- /dev/null +++ b/template.go @@ -0,0 +1,14 @@ +package main + +var tpltext = ` + + + +{{.Title}} + + +
+{{range .Lines}} {{if .Link}}({{.Type}}) {{.Text}}{{else}}      {{.Text}}{{end}}
+{{end}}
+ +` -- cgit v1.2.3-70-g09d2