From 8e084b5697a1cb84a3ce87ec0355d7a9171c4d57 Mon Sep 17 00:00:00 2001 From: James Hillyerd Date: Wed, 24 Feb 2016 22:18:30 -0800 Subject: [PATCH] Refactor web package into two packages: httpd and webui --- {web => httpd}/context.go | 2 +- {web => httpd}/helpers.go | 27 ++++++------ {web => httpd}/helpers_test.go | 16 ++++---- {web => httpd}/rest.go | 2 +- {web => httpd}/server.go | 32 ++++----------- {web => httpd}/template.go | 2 +- inbucket.go | 10 +++-- {web => webui}/mailbox_controller.go | 61 ++++++++++++++-------------- {web => webui}/recent.go | 10 +++-- {web => webui}/rest_test.go | 8 ++-- {web => webui}/root_controller.go | 11 ++--- webui/routes.go | 23 +++++++++++ 12 files changed, 112 insertions(+), 92 deletions(-) rename {web => httpd}/context.go (98%) rename {web => httpd}/helpers.go (69%) rename {web => httpd}/helpers_test.go (55%) rename {web => httpd}/rest.go (96%) rename {web => httpd}/server.go (66%) rename {web => httpd}/template.go (99%) rename {web => webui}/mailbox_controller.go (87%) rename {web => webui}/recent.go (81%) rename {web => webui}/rest_test.go (98%) rename {web => webui}/root_controller.go (73%) create mode 100644 webui/routes.go diff --git a/web/context.go b/httpd/context.go similarity index 98% rename from web/context.go rename to httpd/context.go index b23891b..e6fdc39 100644 --- a/web/context.go +++ b/httpd/context.go @@ -1,4 +1,4 @@ -package web +package httpd import ( "net/http" diff --git a/web/helpers.go b/httpd/helpers.go similarity index 69% rename from web/helpers.go rename to httpd/helpers.go index 6aa7c99..a5f66c6 100644 --- a/web/helpers.go +++ b/httpd/helpers.go @@ -1,4 +1,4 @@ -package web +package httpd import ( "fmt" @@ -13,16 +13,17 @@ import ( // TemplateFuncs declares functions made available to all templates (including partials) var TemplateFuncs = template.FuncMap{ - "friendlyTime": friendlyTime, - "reverse": reverse, - "textToHtml": textToHTML, + "friendlyTime": FriendlyTime, + "reverse": Reverse, + "textToHtml": TextToHTML, } // From http://daringfireball.net/2010/07/improved_regex_for_matching_urls var urlRE = regexp.MustCompile("(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))") -// Friendly date & time rendering -func friendlyTime(t time.Time) template.HTML { +// FriendlyTime renders a timestamp in a friendly fashion: 03:04:05 PM if same day, +// otherwise Mon Jan 2, 2006 +func FriendlyTime(t time.Time) template.HTML { ty, tm, td := t.Date() ny, nm, nd := time.Now().Date() if (ty == ny) && (tm == nm) && (td == nd) { @@ -31,8 +32,8 @@ func friendlyTime(t time.Time) template.HTML { return template.HTML(t.Format("Mon Jan 2, 2006")) } -// Reversable routing function (shared with templates) -func reverse(name string, things ...interface{}) string { +// Reverse routing function (shared with templates) +func Reverse(name string, things ...interface{}) string { // Convert the things to strings strs := make([]string, len(things)) for i, th := range things { @@ -47,17 +48,17 @@ func reverse(name string, things ...interface{}) string { return u.Path } -// textToHtml takes plain text, escapes it and tries to pretty it up for +// TextToHTML takes plain text, escapes it and tries to pretty it up for // HTML display -func textToHTML(text string) template.HTML { +func TextToHTML(text string) template.HTML { text = html.EscapeString(text) - text = urlRE.ReplaceAllStringFunc(text, wrapURL) + text = urlRE.ReplaceAllStringFunc(text, WrapURL) replacer := strings.NewReplacer("\r\n", "
\n", "\r", "
\n", "\n", "
\n") return template.HTML(replacer.Replace(text)) } -// wrapUrl wraps a tag around the provided URL -func wrapURL(url string) string { +// WrapURL wraps a tag around the provided URL +func WrapURL(url string) string { unescaped := strings.Replace(url, "&", "&", -1) return fmt.Sprintf("%s", unescaped, url) } diff --git a/web/helpers_test.go b/httpd/helpers_test.go similarity index 55% rename from web/helpers_test.go rename to httpd/helpers_test.go index ca7837d..fe0ca5c 100644 --- a/web/helpers_test.go +++ b/httpd/helpers_test.go @@ -1,4 +1,4 @@ -package web +package httpd import ( "html/template" @@ -9,22 +9,22 @@ import ( func TestTextToHtml(t *testing.T) { // Identity - assert.Equal(t, textToHTML("html"), template.HTML("html")) + assert.Equal(t, TextToHTML("html"), template.HTML("html")) // Check it escapes - assert.Equal(t, textToHTML(""), template.HTML("<html>")) + assert.Equal(t, TextToHTML(""), template.HTML("<html>")) // Check for linebreaks - assert.Equal(t, textToHTML("line\nbreak"), template.HTML("line
\nbreak")) - assert.Equal(t, textToHTML("line\r\nbreak"), template.HTML("line
\nbreak")) - assert.Equal(t, textToHTML("line\rbreak"), template.HTML("line
\nbreak")) + assert.Equal(t, TextToHTML("line\nbreak"), template.HTML("line
\nbreak")) + assert.Equal(t, TextToHTML("line\r\nbreak"), template.HTML("line
\nbreak")) + assert.Equal(t, TextToHTML("line\rbreak"), template.HTML("line
\nbreak")) } func TestURLDetection(t *testing.T) { assert.Equal(t, - textToHTML("http://google.com/"), + TextToHTML("http://google.com/"), template.HTML("http://google.com/")) assert.Equal(t, - textToHTML("http://a.com/?q=a&n=v"), + TextToHTML("http://a.com/?q=a&n=v"), template.HTML("http://a.com/?q=a&n=v")) } diff --git a/web/rest.go b/httpd/rest.go similarity index 96% rename from web/rest.go rename to httpd/rest.go index aa9d864..805bbc9 100644 --- a/web/rest.go +++ b/httpd/rest.go @@ -1,4 +1,4 @@ -package web +package httpd import ( "encoding/json" diff --git a/web/server.go b/httpd/server.go similarity index 66% rename from web/server.go rename to httpd/server.go index 928a53d..7959741 100644 --- a/web/server.go +++ b/httpd/server.go @@ -1,5 +1,5 @@ -// Package web provides Inbucket's web GUI and RESTful API -package web +// Package httpd provides the plumbing for Inbucket's web GUI and RESTful API +package httpd import ( "fmt" @@ -15,14 +15,16 @@ import ( "github.com/jhillyerd/inbucket/smtpd" ) -type handler func(http.ResponseWriter, *http.Request, *Context) error +// Handler is a function type that handles an HTTP request in Inbucket +type Handler func(http.ResponseWriter, *http.Request, *Context) error var ( // DataStore is where all the mailboxes and messages live DataStore smtpd.DataStore - // Router sends incoming requests to the correct handler function - Router *mux.Router + // Router is shared between httpd, webui and rest packages. It sends + // incoming requests to the correct handler function + Router = mux.NewRouter() webConfig config.WebConfig listener net.Listener @@ -46,27 +48,11 @@ func setupRoutes(cfg config.WebConfig) { log.Infof("HTTP templates mapped to %q", cfg.TemplateDir) log.Infof("HTTP static content mapped to %q", cfg.PublicDir) - r := mux.NewRouter() // Static content - r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", + Router.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir(cfg.PublicDir)))) - // Root - r.Path("/").Handler(handler(RootIndex)).Name("RootIndex").Methods("GET") - r.Path("/status").Handler(handler(RootStatus)).Name("RootStatus").Methods("GET") - r.Path("/link/{name}/{id}").Handler(handler(MailboxLink)).Name("MailboxLink").Methods("GET") - r.Path("/mailbox").Handler(handler(MailboxIndex)).Name("MailboxIndex").Methods("GET") - r.Path("/mailbox/{name}").Handler(handler(MailboxList)).Name("MailboxList").Methods("GET") - r.Path("/mailbox/{name}").Handler(handler(MailboxPurge)).Name("MailboxPurge").Methods("DELETE") - r.Path("/mailbox/{name}/{id}").Handler(handler(MailboxShow)).Name("MailboxShow").Methods("GET") - r.Path("/mailbox/{name}/{id}/html").Handler(handler(MailboxHTML)).Name("MailboxHtml").Methods("GET") - r.Path("/mailbox/{name}/{id}/source").Handler(handler(MailboxSource)).Name("MailboxSource").Methods("GET") - r.Path("/mailbox/{name}/{id}").Handler(handler(MailboxDelete)).Name("MailboxDelete").Methods("DELETE") - r.Path("/mailbox/dattach/{name}/{id}/{num}/{file}").Handler(handler(MailboxDownloadAttach)).Name("MailboxDownloadAttach").Methods("GET") - r.Path("/mailbox/vattach/{name}/{id}/{num}/{file}").Handler(handler(MailboxViewAttach)).Name("MailboxViewAttach").Methods("GET") - // Register w/ HTTP - Router = r http.Handle("/", Router) } @@ -112,7 +98,7 @@ func Stop() { } // ServeHTTP builds the context and passes onto the real handler -func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { +func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { // Create the context ctx, err := NewContext(req) if err != nil { diff --git a/web/template.go b/httpd/template.go similarity index 99% rename from web/template.go rename to httpd/template.go index 61c9b84..3aa81ce 100644 --- a/web/template.go +++ b/httpd/template.go @@ -1,4 +1,4 @@ -package web +package httpd import ( "html/template" diff --git a/inbucket.go b/inbucket.go index d158712..abb24ea 100644 --- a/inbucket.go +++ b/inbucket.go @@ -12,10 +12,11 @@ import ( "time" "github.com/jhillyerd/inbucket/config" + "github.com/jhillyerd/inbucket/httpd" "github.com/jhillyerd/inbucket/log" "github.com/jhillyerd/inbucket/pop3d" "github.com/jhillyerd/inbucket/smtpd" - "github.com/jhillyerd/inbucket/web" + "github.com/jhillyerd/inbucket/webui" ) var ( @@ -122,8 +123,9 @@ func main() { ds := smtpd.DefaultFileDataStore() // Start HTTP server - web.Initialize(config.GetWebConfig(), ds) - go web.Start() + httpd.Initialize(config.GetWebConfig(), ds) + webui.SetupRoutes(httpd.Router) + go httpd.Start() // Start POP3 server pop3Server = pop3d.New() @@ -178,7 +180,7 @@ func signalProcessor(c <-chan os.Signal) { // Initiate shutdown log.Infof("Received SIGTERM, shutting down") go timedExit() - web.Stop() + httpd.Stop() if smtpServer != nil { smtpServer.Stop() } else { diff --git a/web/mailbox_controller.go b/webui/mailbox_controller.go similarity index 87% rename from web/mailbox_controller.go rename to webui/mailbox_controller.go index d02d82f..13e9341 100644 --- a/web/mailbox_controller.go +++ b/webui/mailbox_controller.go @@ -1,4 +1,4 @@ -package web +package webui import ( "fmt" @@ -9,6 +9,7 @@ import ( "strconv" "time" + "github.com/jhillyerd/inbucket/httpd" "github.com/jhillyerd/inbucket/log" "github.com/jhillyerd/inbucket/smtpd" ) @@ -42,28 +43,28 @@ type JSONMessageBody struct { } // MailboxIndex renders the index page for a particular mailbox -func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Form values must be validated manually name := req.FormValue("name") selected := req.FormValue("id") if len(name) == 0 { ctx.Session.AddFlash("Account name is required", "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } name, err = smtpd.ParseMailboxName(name) if err != nil { ctx.Session.AddFlash(err.Error(), "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } // Remember this mailbox was visited RememberMailbox(ctx, name) - return RenderTemplate("mailbox/index.html", w, map[string]interface{}{ + return httpd.RenderTemplate("mailbox/index.html", w, map[string]interface{}{ "ctx": ctx, "name": name, "selected": selected, @@ -71,23 +72,23 @@ func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err e } // MailboxLink handles pretty links to a particular message. Renders a redirect -func MailboxLink(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxLink(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) if err != nil { ctx.Session.AddFlash(err.Error(), "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } - uri := fmt.Sprintf("%s?name=%s&id=%s", reverse("MailboxIndex"), name, id) + uri := fmt.Sprintf("%s?name=%s&id=%s", httpd.Reverse("MailboxIndex"), name, id) http.Redirect(w, req, uri, http.StatusSeeOther) return nil } // MailboxList renders a list of messages in a mailbox. Renders JSON or a partial -func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxList(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) if err != nil { @@ -117,10 +118,10 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err er Size: msg.Size(), } } - return RenderJSON(w, jmessages) + return httpd.RenderJSON(w, jmessages) } - return RenderPartial("mailbox/_list.html", w, map[string]interface{}{ + return httpd.RenderPartial("mailbox/_list.html", w, map[string]interface{}{ "ctx": ctx, "name": name, "messages": messages, @@ -128,7 +129,7 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err er } // MailboxShow renders a particular message from a mailbox. Renders JSON or a partial -func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) @@ -159,7 +160,7 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err er } if ctx.IsJSON { - return RenderJSON(w, + return httpd.RenderJSON(w, &JSONMessage{ Mailbox: name, ID: msg.ID(), @@ -175,10 +176,10 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err er }) } - body := template.HTML(textToHTML(mime.Text)) + body := template.HTML(httpd.TextToHTML(mime.Text)) htmlAvailable := mime.Html != "" - return RenderPartial("mailbox/_show.html", w, map[string]interface{}{ + return httpd.RenderPartial("mailbox/_show.html", w, map[string]interface{}{ "ctx": ctx, "name": name, "message": msg, @@ -189,7 +190,7 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err er } // MailboxPurge deletes all messages from a mailbox. Renders JSON or text/plain OK -func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) if err != nil { @@ -208,7 +209,7 @@ func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *Context) (err e log.Tracef("HTTP purged mailbox for %q", name) if ctx.IsJSON { - return RenderJSON(w, "OK") + return httpd.RenderJSON(w, "OK") } w.Header().Set("Content-Type", "text/plain") @@ -219,7 +220,7 @@ func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *Context) (err e } // MailboxHTML displays the HTML content of a message. Renders a partial -func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) @@ -246,7 +247,7 @@ func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *Context) (err er } w.Header().Set("Content-Type", "text/html; charset=UTF-8") - return RenderPartial("mailbox/_html.html", w, map[string]interface{}{ + return httpd.RenderPartial("mailbox/_html.html", w, map[string]interface{}{ "ctx": ctx, "name": name, "message": message, @@ -256,7 +257,7 @@ func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *Context) (err er } // MailboxSource displays the raw source of a message, including headers. Renders text/plain -func MailboxSource(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxSource(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) @@ -291,20 +292,20 @@ func MailboxSource(w http.ResponseWriter, req *http.Request, ctx *Context) (err // MailboxDownloadAttach sends the attachment to the client; disposition: // attachment, type: application/octet-stream -func MailboxDownloadAttach(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxDownloadAttach(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) if err != nil { ctx.Session.AddFlash(err.Error(), "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } numStr := ctx.Vars["num"] num, err := strconv.ParseUint(numStr, 10, 32) if err != nil { ctx.Session.AddFlash("Attachment number must be unsigned numeric", "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } @@ -328,7 +329,7 @@ func MailboxDownloadAttach(w http.ResponseWriter, req *http.Request, ctx *Contex } if int(num) >= len(body.Attachments) { ctx.Session.AddFlash("Attachment number too high", "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } part := body.Attachments[num] @@ -342,12 +343,12 @@ func MailboxDownloadAttach(w http.ResponseWriter, req *http.Request, ctx *Contex } // MailboxViewAttach sends the attachment to the client for online viewing -func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) if err != nil { ctx.Session.AddFlash(err.Error(), "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } id := ctx.Vars["id"] @@ -355,7 +356,7 @@ func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) ( num, err := strconv.ParseUint(numStr, 10, 32) if err != nil { ctx.Session.AddFlash("Attachment number must be unsigned numeric", "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } @@ -379,7 +380,7 @@ func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) ( } if int(num) >= len(body.Attachments) { ctx.Session.AddFlash("Attachment number too high", "errors") - http.Redirect(w, req, reverse("RootIndex"), http.StatusSeeOther) + http.Redirect(w, req, httpd.Reverse("RootIndex"), http.StatusSeeOther) return nil } part := body.Attachments[num] @@ -392,7 +393,7 @@ func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) ( } // MailboxDelete removes a particular message from a mailbox. Renders JSON or plain/text OK -func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { // Don't have to validate these aren't empty, Gorilla returns 404 id := ctx.Vars["id"] name, err := smtpd.ParseMailboxName(ctx.Vars["name"]) @@ -419,7 +420,7 @@ func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *Context) (err } if ctx.IsJSON { - return RenderJSON(w, "OK") + return httpd.RenderJSON(w, "OK") } w.Header().Set("Content-Type", "text/plain") diff --git a/web/recent.go b/webui/recent.go similarity index 81% rename from web/recent.go rename to webui/recent.go index 4e1bb5b..14118ac 100644 --- a/web/recent.go +++ b/webui/recent.go @@ -1,4 +1,8 @@ -package web +package webui + +import ( + "github.com/jhillyerd/inbucket/httpd" +) const ( // maximum mailboxes to remember @@ -8,7 +12,7 @@ const ( ) // RememberMailbox manages the list of recently accessed mailboxes stored in the session -func RememberMailbox(ctx *Context, mailbox string) { +func RememberMailbox(ctx *httpd.Context, mailbox string) { recent := RecentMailboxes(ctx) newRecent := make([]string, 1, maxRemembered) newRecent[0] = mailbox @@ -24,7 +28,7 @@ func RememberMailbox(ctx *Context, mailbox string) { } // RecentMailboxes returns a slice of the most recently accessed mailboxes -func RecentMailboxes(ctx *Context) []string { +func RecentMailboxes(ctx *httpd.Context) []string { val := ctx.Session.Values[mailboxKey] recent, _ := val.([]string) return recent diff --git a/web/rest_test.go b/webui/rest_test.go similarity index 98% rename from web/rest_test.go rename to webui/rest_test.go index c7254e0..891ec2d 100644 --- a/web/rest_test.go +++ b/webui/rest_test.go @@ -1,4 +1,4 @@ -package web +package webui import ( "bytes" @@ -15,6 +15,7 @@ import ( "github.com/jhillyerd/go.enmime" "github.com/jhillyerd/inbucket/config" + "github.com/jhillyerd/inbucket/httpd" "github.com/jhillyerd/inbucket/smtpd" "github.com/stretchr/testify/mock" ) @@ -395,7 +396,7 @@ func testRestGet(url string) (*httptest.ResponseRecorder, error) { } w := httptest.NewRecorder() - Router.ServeHTTP(w, req) + httpd.Router.ServeHTTP(w, req) return w, nil } @@ -410,7 +411,8 @@ func setupWebServer(ds smtpd.DataStore) *bytes.Buffer { TemplateDir: "../themes/integral/templates", PublicDir: "../themes/integral/public", } - Initialize(cfg, ds) + httpd.Initialize(cfg, ds) + SetupRoutes(httpd.Router) return buf } diff --git a/web/root_controller.go b/webui/root_controller.go similarity index 73% rename from web/root_controller.go rename to webui/root_controller.go index adcc874..0abaced 100644 --- a/web/root_controller.go +++ b/webui/root_controller.go @@ -1,4 +1,4 @@ -package web +package webui import ( "fmt" @@ -7,23 +7,24 @@ import ( "net/http" "github.com/jhillyerd/inbucket/config" + "github.com/jhillyerd/inbucket/httpd" ) // RootIndex serves the Inbucket landing page -func RootIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func RootIndex(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { greeting, err := ioutil.ReadFile(config.GetWebConfig().GreetingFile) if err != nil { return fmt.Errorf("Failed to load greeting: %v", err) } - return RenderTemplate("root/index.html", w, map[string]interface{}{ + return httpd.RenderTemplate("root/index.html", w, map[string]interface{}{ "ctx": ctx, "greeting": template.HTML(string(greeting)), }) } // RootStatus serves the Inbucket status page -func RootStatus(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) { +func RootStatus(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) { retentionMinutes := config.GetDataStoreConfig().RetentionMinutes smtpListener := fmt.Sprintf("%s:%d", config.GetSMTPConfig().IP4address.String(), config.GetSMTPConfig().IP4port) @@ -31,7 +32,7 @@ func RootStatus(w http.ResponseWriter, req *http.Request, ctx *Context) (err err config.GetPOP3Config().IP4port) webListener := fmt.Sprintf("%s:%d", config.GetWebConfig().IP4address.String(), config.GetWebConfig().IP4port) - return RenderTemplate("root/status.html", w, map[string]interface{}{ + return httpd.RenderTemplate("root/status.html", w, map[string]interface{}{ "ctx": ctx, "version": config.Version, "buildDate": config.BuildDate, diff --git a/webui/routes.go b/webui/routes.go new file mode 100644 index 0000000..5ae15cc --- /dev/null +++ b/webui/routes.go @@ -0,0 +1,23 @@ +// Package webui powers Inbucket's web GUI +package webui + +import ( + "github.com/gorilla/mux" + "github.com/jhillyerd/inbucket/httpd" +) + +// SetupRoutes populates routes for the webui into the provided Router +func SetupRoutes(r *mux.Router) { + r.Path("/").Handler(httpd.Handler(RootIndex)).Name("RootIndex").Methods("GET") + r.Path("/status").Handler(httpd.Handler(RootStatus)).Name("RootStatus").Methods("GET") + r.Path("/link/{name}/{id}").Handler(httpd.Handler(MailboxLink)).Name("MailboxLink").Methods("GET") + r.Path("/mailbox").Handler(httpd.Handler(MailboxIndex)).Name("MailboxIndex").Methods("GET") + r.Path("/mailbox/{name}").Handler(httpd.Handler(MailboxList)).Name("MailboxList").Methods("GET") + r.Path("/mailbox/{name}").Handler(httpd.Handler(MailboxPurge)).Name("MailboxPurge").Methods("DELETE") + r.Path("/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxShow)).Name("MailboxShow").Methods("GET") + r.Path("/mailbox/{name}/{id}/html").Handler(httpd.Handler(MailboxHTML)).Name("MailboxHtml").Methods("GET") + r.Path("/mailbox/{name}/{id}/source").Handler(httpd.Handler(MailboxSource)).Name("MailboxSource").Methods("GET") + r.Path("/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxDelete)).Name("MailboxDelete").Methods("DELETE") + r.Path("/mailbox/dattach/{name}/{id}/{num}/{file}").Handler(httpd.Handler(MailboxDownloadAttach)).Name("MailboxDownloadAttach").Methods("GET") + r.Path("/mailbox/vattach/{name}/{id}/{num}/{file}").Handler(httpd.Handler(MailboxViewAttach)).Name("MailboxViewAttach").Methods("GET") +}