From 3b715b37535f5bb6c96ce6f29a0f3fb1cf9149d6 Mon Sep 17 00:00:00 2001 From: Buddy Sandidge Date: Sat, 12 Nov 2016 19:44:54 -0800 Subject: [PATCH] Move html template to it's own file --- .gitignore | 1 + templates/index.tmpl | 11 +++++++++++ what-is-my-ip.go | 35 ++++++++++++++++++----------------- 3 files changed, 30 insertions(+), 17 deletions(-) create mode 100644 templates/index.tmpl diff --git a/.gitignore b/.gitignore index d149a94..7b23249 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ what-is-my-ip +rice-box.go diff --git a/templates/index.tmpl b/templates/index.tmpl new file mode 100644 index 0000000..81e3d35 --- /dev/null +++ b/templates/index.tmpl @@ -0,0 +1,11 @@ + + + + + What is My IP? + + + +
{{.IP}}
+ + diff --git a/what-is-my-ip.go b/what-is-my-ip.go index 2336640..8516314 100644 --- a/what-is-my-ip.go +++ b/what-is-my-ip.go @@ -1,12 +1,13 @@ package main import ( - "errors" "html/template" "net/http" "os" + "github.com/GeertJohan/go.rice" "github.com/gorilla/pat" + "github.com/pkg/errors" "github.com/urfave/cli" "github.com/urfave/negroni" ) @@ -59,16 +60,28 @@ func action(c *cli.Context) error { address := c.String("address") certificate := c.String("certificate") key := c.String("key") - handler, service := getHandler(c.StringSlice("header")) + handler, service, err := getHandler(c.StringSlice("header")) + if err != nil { + return err + } service.logger.Printf("listening on %s\n", address) return http.ListenAndServeTLS(address, certificate, key, handler) } -func getHandler(headers []string) (http.Handler, *Server) { +func getHandler(headers []string) (http.Handler, *Server, error) { + logger := NewLogger() + templateBox := rice.MustFindBox("templates") + templateString, err := templateBox.String("index.tmpl") + if err != nil { + wrappedErr := errors.Wrap(err, "Could not read index.tmpl") + logger.Println(wrappedErr) + return nil, nil, wrappedErr + } + service := &Server{ headerNames: headers, logger: NewLogger(), - tmpl: template.Must(template.New("html").Parse(htmlTemplate)), + tmpl: template.Must(template.New("index").Parse(templateString)), } recover := negroni.NewRecovery() @@ -94,17 +107,5 @@ func getHandler(headers []string) (http.Handler, *Server) { n.Use(service.logger) n.UseHandler(router) - return n, service + return n, service, nil } - -const htmlTemplate = ` - - - - What is My IP? - - - -
{{.IP}}
- -`