mirror of
https://github.com/jhillyerd/inbucket.git
synced 2025-12-23 20:47:03 +00:00
Follow meta-linter recommendations for all of Inbucket
- Rename BUILD_DATE to BUILDDATE in goxc - Update travis config - Follow linter recommendations for inbucket.go - Follow linter recommendations for config package - Follow linter recommendations for log package - Follow linter recommendations for pop3d package - Follow linter recommendations for smtpd package - Follow linter recommendations for web package - Fix Id -> ID in templates - Add shebang to REST demo scripts - Add or refine many comments
This commit is contained in:
@@ -9,13 +9,15 @@ import (
|
||||
"github.com/jhillyerd/inbucket/smtpd"
|
||||
)
|
||||
|
||||
// Context is passed into every request handler function
|
||||
type Context struct {
|
||||
Vars map[string]string
|
||||
Session *sessions.Session
|
||||
DataStore smtpd.DataStore
|
||||
IsJson bool
|
||||
IsJSON bool
|
||||
}
|
||||
|
||||
// Close the Context (currently does nothing)
|
||||
func (c *Context) Close() {
|
||||
// Do nothing
|
||||
}
|
||||
@@ -37,6 +39,7 @@ func headerMatch(req *http.Request, name string, value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// NewContext returns a Context for the given HTTP Request
|
||||
func NewContext(req *http.Request) (*Context, error) {
|
||||
vars := mux.Vars(req)
|
||||
sess, err := sessionStore.Get(req, "inbucket")
|
||||
@@ -44,7 +47,7 @@ func NewContext(req *http.Request) (*Context, error) {
|
||||
Vars: vars,
|
||||
Session: sess,
|
||||
DataStore: DataStore,
|
||||
IsJson: headerMatch(req, "Accept", "application/json"),
|
||||
IsJSON: headerMatch(req, "Accept", "application/json"),
|
||||
}
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
|
||||
@@ -11,10 +11,11 @@ import (
|
||||
"github.com/jhillyerd/inbucket/log"
|
||||
)
|
||||
|
||||
// TemplateFuncs declares functions made available to all templates (including partials)
|
||||
var TemplateFuncs = template.FuncMap{
|
||||
"friendlyTime": friendlyTime,
|
||||
"reverse": reverse,
|
||||
"textToHtml": textToHtml,
|
||||
"textToHtml": textToHTML,
|
||||
}
|
||||
|
||||
// From http://daringfireball.net/2010/07/improved_regex_for_matching_urls
|
||||
@@ -40,7 +41,7 @@ func reverse(name string, things ...interface{}) string {
|
||||
// Grab the route
|
||||
u, err := Router.Get(name).URL(strs...)
|
||||
if err != nil {
|
||||
log.LogError("Failed to reverse route: %v", err)
|
||||
log.Errorf("Failed to reverse route: %v", err)
|
||||
return "/ROUTE-ERROR"
|
||||
}
|
||||
return u.Path
|
||||
@@ -48,15 +49,15 @@ func reverse(name string, things ...interface{}) string {
|
||||
|
||||
// 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", "<br/>\n", "\r", "<br/>\n", "\n", "<br/>\n")
|
||||
return template.HTML(replacer.Replace(text))
|
||||
}
|
||||
|
||||
// wrapUrl wraps a <a href> tag around the provided URL
|
||||
func wrapUrl(url string) string {
|
||||
func wrapURL(url string) string {
|
||||
unescaped := strings.Replace(url, "&", "&", -1)
|
||||
return fmt.Sprintf("<a href=\"%s\" target=\"_blank\">%s</a>", unescaped, url)
|
||||
}
|
||||
|
||||
@@ -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("<html>"), template.HTML("<html>"))
|
||||
assert.Equal(t, textToHTML("<html>"), template.HTML("<html>"))
|
||||
|
||||
// Check for linebreaks
|
||||
assert.Equal(t, textToHtml("line\nbreak"), template.HTML("line<br/>\nbreak"))
|
||||
assert.Equal(t, textToHtml("line\r\nbreak"), template.HTML("line<br/>\nbreak"))
|
||||
assert.Equal(t, textToHtml("line\rbreak"), template.HTML("line<br/>\nbreak"))
|
||||
assert.Equal(t, textToHTML("line\nbreak"), template.HTML("line<br/>\nbreak"))
|
||||
assert.Equal(t, textToHTML("line\r\nbreak"), template.HTML("line<br/>\nbreak"))
|
||||
assert.Equal(t, textToHTML("line\rbreak"), template.HTML("line<br/>\nbreak"))
|
||||
}
|
||||
|
||||
func TestURLDetection(t *testing.T) {
|
||||
assert.Equal(t,
|
||||
textToHtml("http://google.com/"),
|
||||
textToHTML("http://google.com/"),
|
||||
template.HTML("<a href=\"http://google.com/\" target=\"_blank\">http://google.com/</a>"))
|
||||
assert.Equal(t,
|
||||
textToHtml("http://a.com/?q=a&n=v"),
|
||||
textToHTML("http://a.com/?q=a&n=v"),
|
||||
template.HTML("<a href=\"http://a.com/?q=a&n=v\" target=\"_blank\">http://a.com/?q=a&n=v</a>"))
|
||||
}
|
||||
|
||||
@@ -13,24 +13,35 @@ import (
|
||||
"github.com/jhillyerd/inbucket/smtpd"
|
||||
)
|
||||
|
||||
type JsonMessageHeader struct {
|
||||
Mailbox, Id, From, Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
// JSONMessageHeader contains the basic header data for a message
|
||||
type JSONMessageHeader struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From string
|
||||
Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
}
|
||||
|
||||
type JsonMessage struct {
|
||||
Mailbox, Id, From, Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
Body *JsonMessageBody
|
||||
Header mail.Header
|
||||
// JSONMessage contains the same data as the header plus a JSONMessageBody
|
||||
type JSONMessage struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From string
|
||||
Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
Body *JSONMessageBody
|
||||
Header mail.Header
|
||||
}
|
||||
|
||||
type JsonMessageBody struct {
|
||||
Text, Html string
|
||||
// JSONMessageBody contains the Text and HTML versions of the message body
|
||||
type JSONMessageBody struct {
|
||||
Text string
|
||||
HTML string `json:"Html"`
|
||||
}
|
||||
|
||||
// MailboxIndex renders the index page for a particular mailbox
|
||||
func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Form values must be validated manually
|
||||
name := req.FormValue("name")
|
||||
@@ -59,6 +70,7 @@ func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err e
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxLink handles pretty links to a particular message
|
||||
func MailboxLink(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -74,6 +86,7 @@ func MailboxLink(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxList renders a list of messages in a mailbox
|
||||
func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
name, err := smtpd.ParseMailboxName(ctx.Vars["name"])
|
||||
@@ -88,21 +101,21 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to get messages for %v: %v", name, err)
|
||||
}
|
||||
log.LogTrace("Got %v messsages", len(messages))
|
||||
log.Tracef("Got %v messsages", len(messages))
|
||||
|
||||
if ctx.IsJson {
|
||||
jmessages := make([]*JsonMessageHeader, len(messages))
|
||||
if ctx.IsJSON {
|
||||
jmessages := make([]*JSONMessageHeader, len(messages))
|
||||
for i, msg := range messages {
|
||||
jmessages[i] = &JsonMessageHeader{
|
||||
jmessages[i] = &JSONMessageHeader{
|
||||
Mailbox: name,
|
||||
Id: msg.Id(),
|
||||
ID: msg.ID(),
|
||||
From: msg.From(),
|
||||
Subject: msg.Subject(),
|
||||
Date: msg.Date(),
|
||||
Size: msg.Size(),
|
||||
}
|
||||
}
|
||||
return RenderJson(w, jmessages)
|
||||
return RenderJSON(w, jmessages)
|
||||
}
|
||||
|
||||
return RenderPartial("mailbox/_list.html", w, map[string]interface{}{
|
||||
@@ -112,6 +125,7 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxShow renders a particular message from a mailbox
|
||||
func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -140,24 +154,24 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
return fmt.Errorf("ReadBody() failed: %v", err)
|
||||
}
|
||||
|
||||
if ctx.IsJson {
|
||||
return RenderJson(w,
|
||||
&JsonMessage{
|
||||
if ctx.IsJSON {
|
||||
return RenderJSON(w,
|
||||
&JSONMessage{
|
||||
Mailbox: name,
|
||||
Id: msg.Id(),
|
||||
ID: msg.ID(),
|
||||
From: msg.From(),
|
||||
Subject: msg.Subject(),
|
||||
Date: msg.Date(),
|
||||
Size: msg.Size(),
|
||||
Header: header.Header,
|
||||
Body: &JsonMessageBody{
|
||||
Body: &JSONMessageBody{
|
||||
Text: mime.Text,
|
||||
Html: mime.Html,
|
||||
HTML: mime.Html,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
body := template.HTML(textToHtml(mime.Text))
|
||||
body := template.HTML(textToHTML(mime.Text))
|
||||
htmlAvailable := mime.Html != ""
|
||||
|
||||
return RenderPartial("mailbox/_show.html", w, map[string]interface{}{
|
||||
@@ -170,6 +184,7 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxPurge deletes all messages from a mailbox
|
||||
func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
name, err := smtpd.ParseMailboxName(ctx.Vars["name"])
|
||||
@@ -183,18 +198,21 @@ func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *Context) (err e
|
||||
if err := mb.Purge(); err != nil {
|
||||
return fmt.Errorf("Mailbox(%q) Purge: %v", name, err)
|
||||
}
|
||||
log.LogTrace("Purged mailbox for %q", name)
|
||||
log.Tracef("Purged mailbox for %q", name)
|
||||
|
||||
if ctx.IsJson {
|
||||
return RenderJson(w, "OK")
|
||||
if ctx.IsJSON {
|
||||
return RenderJSON(w, "OK")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
io.WriteString(w, "OK")
|
||||
if _, err := io.WriteString(w, "OK"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MailboxHtml(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// MailboxHTML displays the HTML content of a message
|
||||
func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *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"])
|
||||
@@ -224,6 +242,7 @@ func MailboxHtml(w http.ResponseWriter, req *http.Request, ctx *Context) (err er
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxSource displays the raw source of a message, including headers
|
||||
func MailboxSource(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -245,10 +264,14 @@ func MailboxSource(w http.ResponseWriter, req *http.Request, ctx *Context) (err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
io.WriteString(w, *raw)
|
||||
if _, err := io.WriteString(w, *raw); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -287,10 +310,13 @@ func MailboxDownloadAttach(w http.ResponseWriter, req *http.Request, ctx *Contex
|
||||
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", "attachment")
|
||||
w.Write(part.Content())
|
||||
if _, err := w.Write(part.Content()); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxViewAttach sends the attachment to the client for online viewing
|
||||
func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
name, err := smtpd.ParseMailboxName(ctx.Vars["name"])
|
||||
@@ -328,10 +354,13 @@ func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *Context) (
|
||||
part := body.Attachments[num]
|
||||
|
||||
w.Header().Set("Content-Type", part.ContentType())
|
||||
w.Write(part.Content())
|
||||
if _, err := w.Write(part.Content()); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxDelete removes a particular message from a mailbox
|
||||
func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -352,11 +381,13 @@ func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *Context) (err
|
||||
return err
|
||||
}
|
||||
|
||||
if ctx.IsJson {
|
||||
return RenderJson(w, "OK")
|
||||
if ctx.IsJSON {
|
||||
return RenderJSON(w, "OK")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
io.WriteString(w, "OK")
|
||||
if _, err := io.WriteString(w, "OK"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RenderJson(w http.ResponseWriter, data interface{}) error {
|
||||
// RenderJSON sets the correct HTTP headers for JSON, then writes the specified
|
||||
// data (typically a struct) encoded in JSON
|
||||
func RenderJSON(w http.ResponseWriter, data interface{}) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Expires", "-1")
|
||||
enc := json.NewEncoder(w)
|
||||
|
||||
@@ -19,31 +19,42 @@ import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
type OutputJsonHeader struct {
|
||||
Mailbox, Id, From, Subject, Date string
|
||||
Size int
|
||||
// OutputJSONHeader holds the received Header
|
||||
type OutputJSONHeader struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject, Date string
|
||||
Size int
|
||||
}
|
||||
|
||||
type OutputJsonMessage struct {
|
||||
Mailbox, Id, From, Subject, Date string
|
||||
Size int
|
||||
Header map[string][]string
|
||||
Body struct {
|
||||
Text, Html string
|
||||
// OutputJSONMessage holds the received Message
|
||||
type OutputJSONMessage struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject, Date string
|
||||
Size int
|
||||
Header map[string][]string
|
||||
Body struct {
|
||||
Text string
|
||||
HTML string `json:"Html"`
|
||||
}
|
||||
}
|
||||
|
||||
// InputMessageData holds the message we want to test
|
||||
type InputMessageData struct {
|
||||
Mailbox, Id, From, Subject string
|
||||
Date time.Time
|
||||
Size int
|
||||
Header mail.Header
|
||||
Html, Text string
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject string
|
||||
Date time.Time
|
||||
Size int
|
||||
Header mail.Header
|
||||
HTML string `json:"Html"`
|
||||
Text string
|
||||
}
|
||||
|
||||
func (d *InputMessageData) MockMessage() *MockMessage {
|
||||
msg := &MockMessage{}
|
||||
msg.On("Id").Return(d.Id)
|
||||
msg.On("ID").Return(d.ID)
|
||||
msg.On("From").Return(d.From)
|
||||
msg.On("Subject").Return(d.Subject)
|
||||
msg.On("Date").Return(d.Date)
|
||||
@@ -54,20 +65,20 @@ func (d *InputMessageData) MockMessage() *MockMessage {
|
||||
msg.On("ReadHeader").Return(gomsg, nil)
|
||||
body := &enmime.MIMEBody{
|
||||
Text: d.Text,
|
||||
Html: d.Html,
|
||||
Html: d.HTML,
|
||||
}
|
||||
msg.On("ReadBody").Return(body, nil)
|
||||
return msg
|
||||
}
|
||||
|
||||
func (d *InputMessageData) CompareToJsonHeader(j *OutputJsonHeader) (errors []string) {
|
||||
func (d *InputMessageData) CompareToJSONHeader(j *OutputJSONHeader) (errors []string) {
|
||||
if d.Mailbox != j.Mailbox {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Mailbox=%q, got %q", d.Mailbox,
|
||||
j.Mailbox))
|
||||
}
|
||||
if d.Id != j.Id {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.Id,
|
||||
j.Id))
|
||||
if d.ID != j.ID {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.ID,
|
||||
j.ID))
|
||||
}
|
||||
if d.From != j.From {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.From=%q, got %q", d.From,
|
||||
@@ -90,14 +101,14 @@ func (d *InputMessageData) CompareToJsonHeader(j *OutputJsonHeader) (errors []st
|
||||
return errors
|
||||
}
|
||||
|
||||
func (d *InputMessageData) CompareToJsonMessage(j *OutputJsonMessage) (errors []string) {
|
||||
func (d *InputMessageData) CompareToJSONMessage(j *OutputJSONMessage) (errors []string) {
|
||||
if d.Mailbox != j.Mailbox {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Mailbox=%q, got %q", d.Mailbox,
|
||||
j.Mailbox))
|
||||
}
|
||||
if d.Id != j.Id {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.Id,
|
||||
j.Id))
|
||||
if d.ID != j.ID {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.ID,
|
||||
j.ID))
|
||||
}
|
||||
if d.From != j.From {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.From=%q, got %q", d.From,
|
||||
@@ -120,9 +131,9 @@ func (d *InputMessageData) CompareToJsonMessage(j *OutputJsonMessage) (errors []
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Text=%q, got %q", d.Text,
|
||||
j.Body.Text))
|
||||
}
|
||||
if d.Html != j.Body.Html {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Html=%q, got %q", d.Html,
|
||||
j.Body.Html))
|
||||
if d.HTML != j.Body.HTML {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Html=%q, got %q", d.HTML,
|
||||
j.Body.HTML))
|
||||
}
|
||||
for k, vals := range d.Header {
|
||||
jvals, ok := j.Header[k]
|
||||
@@ -191,7 +202,7 @@ func TestRestMailboxList(t *testing.T) {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
io.Copy(os.Stderr, logbuf)
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
|
||||
// Test MailboxFor error
|
||||
@@ -211,14 +222,14 @@ func TestRestMailboxList(t *testing.T) {
|
||||
// Test JSON message headers
|
||||
data1 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
Id: "0001",
|
||||
ID: "0001",
|
||||
From: "from1",
|
||||
Subject: "subject 1",
|
||||
Date: time.Date(2012, 2, 1, 10, 11, 12, 253, time.FixedZone("PST", -800)),
|
||||
}
|
||||
data2 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
Id: "0002",
|
||||
ID: "0002",
|
||||
From: "from2",
|
||||
Subject: "subject 2",
|
||||
Date: time.Date(2012, 7, 1, 10, 11, 12, 253, time.FixedZone("PDT", -700)),
|
||||
@@ -241,19 +252,19 @@ func TestRestMailboxList(t *testing.T) {
|
||||
|
||||
// Check JSON
|
||||
dec := json.NewDecoder(w.Body)
|
||||
var result []OutputJsonHeader
|
||||
var result []OutputJSONHeader
|
||||
if err := dec.Decode(&result); err != nil {
|
||||
t.Errorf("Failed to decode JSON: %v", err)
|
||||
}
|
||||
if len(result) != 2 {
|
||||
t.Errorf("Expected 2 results, got %v", len(result))
|
||||
}
|
||||
if errors := data1.CompareToJsonHeader(&result[0]); len(errors) > 0 {
|
||||
if errors := data1.CompareToJSONHeader(&result[0]); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
if errors := data2.CompareToJsonHeader(&result[1]); len(errors) > 0 {
|
||||
if errors := data2.CompareToJSONHeader(&result[1]); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
@@ -263,7 +274,7 @@ func TestRestMailboxList(t *testing.T) {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
io.Copy(os.Stderr, logbuf)
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,7 +322,7 @@ func TestRestMessage(t *testing.T) {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
io.Copy(os.Stderr, logbuf)
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
|
||||
// Test GetMessage error
|
||||
@@ -331,7 +342,7 @@ func TestRestMessage(t *testing.T) {
|
||||
// Test JSON message headers
|
||||
data1 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
Id: "0001",
|
||||
ID: "0001",
|
||||
From: "from1",
|
||||
Subject: "subject 1",
|
||||
Date: time.Date(2012, 2, 1, 10, 11, 12, 253, time.FixedZone("PST", -800)),
|
||||
@@ -339,7 +350,7 @@ func TestRestMessage(t *testing.T) {
|
||||
"To": []string{"fred@fish.com", "keyword@nsa.gov"},
|
||||
},
|
||||
Text: "This is some text",
|
||||
Html: "This is some HTML",
|
||||
HTML: "This is some HTML",
|
||||
}
|
||||
goodbox := &MockMailbox{}
|
||||
ds.On("MailboxFor", "good").Return(goodbox, nil)
|
||||
@@ -358,11 +369,11 @@ func TestRestMessage(t *testing.T) {
|
||||
|
||||
// Check JSON
|
||||
dec := json.NewDecoder(w.Body)
|
||||
var result OutputJsonMessage
|
||||
var result OutputJSONMessage
|
||||
if err := dec.Decode(&result); err != nil {
|
||||
t.Errorf("Failed to decode JSON: %v", err)
|
||||
}
|
||||
if errors := data1.CompareToJsonMessage(&result); len(errors) > 0 {
|
||||
if errors := data1.CompareToJSONMessage(&result); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
@@ -372,7 +383,7 @@ func TestRestMessage(t *testing.T) {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
io.Copy(os.Stderr, logbuf)
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,7 +415,7 @@ func setupWebServer(ds smtpd.DataStore) *bytes.Buffer {
|
||||
return buf
|
||||
}
|
||||
|
||||
// Mock DataStore object
|
||||
// MockDataStore used to mock DataStore interface
|
||||
type MockDataStore struct {
|
||||
mock.Mock
|
||||
}
|
||||
@@ -419,7 +430,7 @@ func (m *MockDataStore) AllMailboxes() ([]smtpd.Mailbox, error) {
|
||||
return args.Get(0).([]smtpd.Mailbox), args.Error(1)
|
||||
}
|
||||
|
||||
// Mock Mailbox object
|
||||
// MockMailbox used to mock Mailbox interface
|
||||
type MockMailbox struct {
|
||||
mock.Mock
|
||||
}
|
||||
@@ -454,7 +465,7 @@ type MockMessage struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockMessage) Id() string {
|
||||
func (m *MockMessage) ID() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/jhillyerd/inbucket/config"
|
||||
)
|
||||
|
||||
// RootIndex serves the Inbucket landing page
|
||||
func RootIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
greeting, err := ioutil.ReadFile(config.GetWebConfig().GreetingFile)
|
||||
if err != nil {
|
||||
@@ -21,18 +22,19 @@ func RootIndex(w http.ResponseWriter, req *http.Request, ctx *Context) (err erro
|
||||
})
|
||||
}
|
||||
|
||||
// RootStatus serves the Inbucket status page
|
||||
func RootStatus(w http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
|
||||
retentionMinutes := config.GetDataStoreConfig().RetentionMinutes
|
||||
smtpListener := fmt.Sprintf("%s:%d", config.GetSmtpConfig().Ip4address.String(),
|
||||
config.GetSmtpConfig().Ip4port)
|
||||
pop3Listener := fmt.Sprintf("%s:%d", config.GetPop3Config().Ip4address.String(),
|
||||
config.GetPop3Config().Ip4port)
|
||||
webListener := fmt.Sprintf("%s:%d", config.GetWebConfig().Ip4address.String(),
|
||||
config.GetWebConfig().Ip4port)
|
||||
smtpListener := fmt.Sprintf("%s:%d", config.GetSMTPConfig().IP4address.String(),
|
||||
config.GetSMTPConfig().IP4port)
|
||||
pop3Listener := fmt.Sprintf("%s:%d", config.GetPOP3Config().IP4address.String(),
|
||||
config.GetPOP3Config().IP4port)
|
||||
webListener := fmt.Sprintf("%s:%d", config.GetWebConfig().IP4address.String(),
|
||||
config.GetWebConfig().IP4port)
|
||||
return RenderTemplate("root/status.html", w, map[string]interface{}{
|
||||
"ctx": ctx,
|
||||
"version": config.VERSION,
|
||||
"buildDate": config.BUILD_DATE,
|
||||
"version": config.Version,
|
||||
"buildDate": config.BuildDate,
|
||||
"retentionMinutes": retentionMinutes,
|
||||
"smtpListener": smtpListener,
|
||||
"pop3Listener": pop3Listener,
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
/*
|
||||
The web package contains all the code to provide Inbucket's web GUI
|
||||
*/
|
||||
// Package web provides Inbucket's web GUI and RESTful API
|
||||
package web
|
||||
|
||||
import (
|
||||
@@ -19,12 +17,18 @@ import (
|
||||
|
||||
type handler func(http.ResponseWriter, *http.Request, *Context) error
|
||||
|
||||
var webConfig config.WebConfig
|
||||
var DataStore smtpd.DataStore
|
||||
var Router *mux.Router
|
||||
var listener net.Listener
|
||||
var sessionStore sessions.Store
|
||||
var shutdown bool
|
||||
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
|
||||
|
||||
webConfig config.WebConfig
|
||||
listener net.Listener
|
||||
sessionStore sessions.Store
|
||||
shutdown bool
|
||||
)
|
||||
|
||||
// Initialize sets up things for unit tests or the Start() method
|
||||
func Initialize(cfg config.WebConfig, ds smtpd.DataStore) {
|
||||
@@ -39,8 +43,8 @@ func Initialize(cfg config.WebConfig, ds smtpd.DataStore) {
|
||||
}
|
||||
|
||||
func setupRoutes(cfg config.WebConfig) {
|
||||
log.LogInfo("Theme templates mapped to '%v'", cfg.TemplateDir)
|
||||
log.LogInfo("Theme static content mapped to '%v'", cfg.PublicDir)
|
||||
log.Infof("Theme templates mapped to '%v'", cfg.TemplateDir)
|
||||
log.Infof("Theme static content mapped to '%v'", cfg.PublicDir)
|
||||
|
||||
r := mux.NewRouter()
|
||||
// Static content
|
||||
@@ -55,7 +59,7 @@ func setupRoutes(cfg config.WebConfig) {
|
||||
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}/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")
|
||||
@@ -66,9 +70,9 @@ func setupRoutes(cfg config.WebConfig) {
|
||||
http.Handle("/", Router)
|
||||
}
|
||||
|
||||
// Start() the web server
|
||||
// Start begins listening for HTTP requests
|
||||
func Start() {
|
||||
addr := fmt.Sprintf("%v:%v", webConfig.Ip4address, webConfig.Ip4port)
|
||||
addr := fmt.Sprintf("%v:%v", webConfig.IP4address, webConfig.IP4port)
|
||||
server := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: nil,
|
||||
@@ -77,30 +81,33 @@ func Start() {
|
||||
}
|
||||
|
||||
// We don't use ListenAndServe because it lacks a way to close the listener
|
||||
log.LogInfo("HTTP listening on TCP4 %v", addr)
|
||||
log.Infof("HTTP listening on TCP4 %v", addr)
|
||||
var err error
|
||||
listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
log.LogError("HTTP failed to start TCP4 listener: %v", err)
|
||||
log.Errorf("HTTP failed to start TCP4 listener: %v", err)
|
||||
// TODO More graceful early-shutdown procedure
|
||||
panic(err)
|
||||
}
|
||||
|
||||
err = server.Serve(listener)
|
||||
if shutdown {
|
||||
log.LogTrace("HTTP server shutting down on request")
|
||||
log.Tracef("HTTP server shutting down on request")
|
||||
} else if err != nil {
|
||||
log.LogError("HTTP server failed: %v", err)
|
||||
log.Errorf("HTTP server failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Stop shuts down the HTTP server
|
||||
func Stop() {
|
||||
log.LogTrace("HTTP shutdown requested")
|
||||
log.Tracef("HTTP shutdown requested")
|
||||
shutdown = true
|
||||
if listener != nil {
|
||||
listener.Close()
|
||||
if err := listener.Close(); err != nil {
|
||||
log.Errorf("Error closing HTTP listener: %v", err)
|
||||
}
|
||||
} else {
|
||||
log.LogError("HTTP listener was nil during shutdown")
|
||||
log.Errorf("HTTP listener was nil during shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +116,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
// Create the context
|
||||
ctx, err := NewContext(req)
|
||||
if err != nil {
|
||||
log.LogError("Failed to create context: %v", err)
|
||||
log.Errorf("Failed to create context: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -117,21 +124,23 @@ func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
// Run the handler, grab the error, and report it
|
||||
buf := new(httpbuf.Buffer)
|
||||
log.LogTrace("Web: %v %v %v %v", req.RemoteAddr, req.Proto, req.Method, req.RequestURI)
|
||||
log.Tracef("Web: %v %v %v %v", req.RemoteAddr, req.Proto, req.Method, req.RequestURI)
|
||||
err = h(buf, req, ctx)
|
||||
if err != nil {
|
||||
log.LogError("Error handling %v: %v", req.RequestURI, err)
|
||||
log.Errorf("Error handling %v: %v", req.RequestURI, err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Save the session
|
||||
if err = ctx.Session.Save(req, buf); err != nil {
|
||||
log.LogError("Failed to save session: %v", err)
|
||||
log.Errorf("Failed to save session: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Apply the buffered response to the writer
|
||||
buf.Apply(w)
|
||||
if _, err = buf.Apply(w); err != nil {
|
||||
log.Errorf("Failed to write response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ var cachedPartials = map[string]*template.Template{}
|
||||
func RenderTemplate(name string, w http.ResponseWriter, data interface{}) error {
|
||||
t, err := ParseTemplate(name, false)
|
||||
if err != nil {
|
||||
log.LogError("Error in template '%v': %v", name, err)
|
||||
log.Errorf("Error in template '%v': %v", name, err)
|
||||
return err
|
||||
}
|
||||
w.Header().Set("Expires", "-1")
|
||||
@@ -32,7 +32,7 @@ func RenderTemplate(name string, w http.ResponseWriter, data interface{}) error
|
||||
func RenderPartial(name string, w http.ResponseWriter, data interface{}) error {
|
||||
t, err := ParseTemplate(name, true)
|
||||
if err != nil {
|
||||
log.LogError("Error in template '%v': %v", name, err)
|
||||
log.Errorf("Error in template '%v': %v", name, err)
|
||||
return err
|
||||
}
|
||||
w.Header().Set("Expires", "-1")
|
||||
@@ -51,7 +51,7 @@ func ParseTemplate(name string, partial bool) (*template.Template, error) {
|
||||
|
||||
tempPath := strings.Replace(name, "/", string(filepath.Separator), -1)
|
||||
tempFile := filepath.Join(webConfig.TemplateDir, tempPath)
|
||||
log.LogTrace("Parsing template %v", tempFile)
|
||||
log.Tracef("Parsing template %v", tempFile)
|
||||
|
||||
var err error
|
||||
var t *template.Template
|
||||
@@ -71,10 +71,10 @@ func ParseTemplate(name string, partial bool) (*template.Template, error) {
|
||||
// Allows us to disable caching for theme development
|
||||
if webConfig.TemplateCache {
|
||||
if partial {
|
||||
log.LogTrace("Caching partial %v", name)
|
||||
log.Tracef("Caching partial %v", name)
|
||||
cachedTemplates[name] = t
|
||||
} else {
|
||||
log.LogTrace("Caching template %v", name)
|
||||
log.Tracef("Caching template %v", name)
|
||||
cachedTemplates[name] = t
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user