MailHog/mailhog/http/server.go

83 lines
2.1 KiB
Go
Raw Normal View History

2014-04-20 15:35:59 +01:00
package http
import (
2014-04-20 16:05:50 +01:00
"encoding/json"
2014-04-20 15:35:59 +01:00
"net/http"
2014-04-20 17:09:06 +01:00
"regexp"
2014-04-20 15:35:59 +01:00
"github.com/ian-kent/MailHog/mailhog"
"github.com/ian-kent/MailHog/mailhog/templates"
2014-04-20 16:05:50 +01:00
"github.com/ian-kent/MailHog/mailhog/storage"
2014-04-20 15:35:59 +01:00
"github.com/ian-kent/MailHog/mailhog/templates/images"
"github.com/ian-kent/MailHog/mailhog/templates/js"
)
var exitChannel chan int
2014-04-20 16:05:50 +01:00
var config *mailhog.Config
2014-04-20 15:35:59 +01:00
func web_exit(w http.ResponseWriter, r *http.Request) {
web_headers(w)
2014-04-20 16:05:50 +01:00
w.Write([]byte("Exiting MailHog!"))
2014-04-20 15:35:59 +01:00
exitChannel <- 1
}
func web_index(w http.ResponseWriter, r *http.Request) {
web_headers(w)
2014-04-20 16:05:50 +01:00
w.Write([]byte(web_render(templates.Index())))
2014-04-20 15:35:59 +01:00
}
func web_jscontroller(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript")
2014-04-20 16:05:50 +01:00
w.Write([]byte(js.Controllers()))
2014-04-20 15:35:59 +01:00
}
func web_imgcontroller(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.Write(images.Hog())
}
func web_render(content string) string {
return templates.Layout(content)
}
func web_headers(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html")
}
2014-04-20 16:05:50 +01:00
func api_messages(w http.ResponseWriter, r *http.Request) {
2014-04-20 17:09:06 +01:00
re, _ := regexp.Compile("/api/v1/messages/([0-9a-f]+)/delete")
match := re.FindStringSubmatch(r.URL.Path)
if len(match) > 0 {
api_delete_one(w, r, match[1])
return
}
// TODO start, limit
2014-04-20 16:05:50 +01:00
messages, _ := storage.List(config, 0, 1000)
bytes, _ := json.Marshal(messages)
w.Header().Set("Content-Type", "text/json")
w.Write(bytes)
}
2014-04-20 17:09:06 +01:00
func api_delete_all(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/json")
storage.DeleteAll(config)
}
func api_delete_one(w http.ResponseWriter, r *http.Request, id string) {
w.Header().Set("Content-Type", "text/json")
storage.DeleteOne(config, id)
}
2014-04-20 15:35:59 +01:00
func Start(exitCh chan int, conf *mailhog.Config) {
exitChannel = exitCh
2014-04-20 16:05:50 +01:00
config = conf
2014-04-20 15:35:59 +01:00
http.HandleFunc("/exit", web_exit)
http.HandleFunc("/js/controllers.js", web_jscontroller)
http.HandleFunc("/images/hog.png", web_imgcontroller)
http.HandleFunc("/", web_index)
2014-04-20 17:09:06 +01:00
http.HandleFunc("/api/v1/messages/", api_messages)
http.HandleFunc("/api/v1/messages/delete", api_delete_all)
2014-04-20 15:35:59 +01:00
http.ListenAndServe(conf.HTTPBindAddr, nil)
}