package response import ( "log" "net/http" "lishwist/http/session" "lishwist/http/templates" "github.com/Teajey/rsvp" ) type ServeMux struct { inner *rsvp.ServeMux store *session.Store } func NewServeMux(store *session.Store) *ServeMux { mux := rsvp.NewServeMux() mux.Config.HtmlTemplate = templates.Template return &ServeMux{ inner: mux, store: store, } } func (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { m.inner.ServeHTTP(w, r) } type Handler interface { ServeHTTP(*Session, http.Header, *http.Request) rsvp.Response } type HandlerFunc func(*Session, http.Header, *http.Request) rsvp.Response func (m *ServeMux) HandleFunc(pattern string, handler HandlerFunc) { m.inner.MiddleHandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) rsvp.Response { session := m.GetSession(r) response := handler(session, w.Header(), r) if session.written { err := session.inner.Save(r, w) if err != nil { log.Printf("Failed to save session: %s\n", err) } } return response }) } func (m *ServeMux) Handle(pattern string, handler Handler) { m.HandleFunc(pattern, handler.ServeHTTP) }