MailHog/mailhog/http/server.go

68 lines
1.9 KiB
Go
Raw Normal View History

2014-04-20 14:35:59 +00:00
package http
import (
2014-04-20 16:09:06 +00:00
"regexp"
2014-04-20 18:49:05 +00:00
"net/http"
2014-04-27 15:06:58 +00:00
"strings"
2014-04-23 23:22:50 +00:00
"github.com/ian-kent/MailHog/mailhog/config"
2014-04-20 18:49:05 +00:00
"github.com/ian-kent/MailHog/mailhog/http/api"
"github.com/ian-kent/MailHog/mailhog/http/handler"
2014-04-20 14:35:59 +00:00
)
var exitChannel chan int
2014-04-23 23:22:50 +00:00
var cfg *config.Config
2014-04-20 14:35:59 +00:00
2014-04-20 18:49:05 +00:00
func web_exit(w http.ResponseWriter, r *http.Request, route *handler.Route) {
2014-04-20 14:35:59 +00:00
web_headers(w)
2014-04-20 15:05:50 +00:00
w.Write([]byte("Exiting MailHog!"))
2014-04-20 14:35:59 +00:00
exitChannel <- 1
}
2014-04-20 18:49:05 +00:00
func web_index(w http.ResponseWriter, r *http.Request, route *handler.Route) {
2014-04-20 14:35:59 +00:00
web_headers(w)
2014-04-27 15:06:58 +00:00
data, _ := cfg.Assets("assets/templates/index.html")
w.Write([]byte(web_render(string(data))))
2014-04-20 14:35:59 +00:00
}
2014-04-20 18:49:05 +00:00
func web_jscontroller(w http.ResponseWriter, r *http.Request, route *handler.Route) {
2014-04-20 14:35:59 +00:00
w.Header().Set("Content-Type", "text/javascript")
2014-04-27 15:06:58 +00:00
data, _ := cfg.Assets("assets/js/controllers.js")
w.Write(data)
2014-04-20 14:35:59 +00:00
}
2014-04-20 18:49:05 +00:00
func web_imgcontroller(w http.ResponseWriter, r *http.Request, route *handler.Route) {
2014-04-20 14:35:59 +00:00
w.Header().Set("Content-Type", "image/png")
2014-04-27 15:06:58 +00:00
data, _ := cfg.Assets("assets/images/hog.png")
w.Write(data)
2014-04-20 14:35:59 +00:00
}
func web_render(content string) string {
2014-04-27 15:06:58 +00:00
data, _ := cfg.Assets("assets/templates/layout.html")
layout := string(data)
html := strings.Replace(layout, "<%= content %>", content, -1)
return html
2014-04-20 14:35:59 +00:00
}
func web_headers(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html")
}
2014-04-23 23:22:50 +00:00
func Start(exitCh chan int, conf *config.Config) {
2014-04-20 14:35:59 +00:00
exitChannel = exitCh
2014-04-23 23:22:50 +00:00
cfg = conf
2014-04-20 15:05:50 +00:00
2014-04-20 18:49:05 +00:00
server := &http.Server{
Addr: conf.HTTPBindAddr,
Handler: &handler.RegexpHandler{},
}
2014-04-20 19:01:53 +00:00
server.Handler.(*handler.RegexpHandler).HandleFunc(regexp.MustCompile("^/exit/?$"), web_exit)
2014-04-20 18:49:05 +00:00
server.Handler.(*handler.RegexpHandler).HandleFunc(regexp.MustCompile("^/js/controllers.js$"), web_jscontroller)
server.Handler.(*handler.RegexpHandler).HandleFunc(regexp.MustCompile("^/images/hog.png$"), web_imgcontroller)
server.Handler.(*handler.RegexpHandler).HandleFunc(regexp.MustCompile("^/$"), web_index)
2014-04-23 23:22:50 +00:00
api.CreateAPIv1(exitCh, conf, server)
2014-04-20 18:49:05 +00:00
server.ListenAndServe()
2014-04-20 14:35:59 +00:00
}