func title(p string) string {
	return strings.TrimSuffix(path.Base(p), path.Ext(p))
}
title gives a backup generated title for a page
package markdown
import (
	"log"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"text/template"
	"time"
	"github.com/tmpim/casket/caskethttp/httpserver"
	"github.com/russross/blackfriday"
)
type Markdown struct {
	Root string
	FileSys http.FileSystem
	Next httpserver.Handler
	Configs []*Config
}
type Config struct {
	Renderer blackfriday.Renderer
	PathScope string
	Extensions map[string]struct{}
	Styles []string
	Scripts []string
	IndexFiles []string
	Template *template.Template
	TemplateFiles map[string]*cachedFileInfo
}
type cachedFileInfo struct {
	path string
	fi   os.FileInfo
}
func (md Markdown) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var cfg *Config
	for _, c := range md.Configs {
		if httpserver.Path(r.URL.Path).Matches(c.PathScope) {  
			cfg = c
			break  
		}
	}
	if cfg == nil {
		return md.Next.ServeHTTP(w, r)  
	}
	switch r.Method {
	case http.MethodGet, http.MethodHead:
	default:
		return http.StatusMethodNotAllowed, nil
	}
	var dirents []os.FileInfo
	var lastModTime time.Time
	fpath := r.URL.Path
	if idx, ok := httpserver.IndexFile(md.FileSys, fpath, cfg.IndexFiles); ok {
		fdp, err := md.FileSys.Open(fpath)
		switch {
		case err == nil:  
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusNotFound, nil
		default:  
			return http.StatusInternalServerError, err
		}
		defer fdp.Close()
		dirents, _ = fdp.Readdir(-1)
		for _, d := range dirents {
			lastModTime = latest(lastModTime, d.ModTime())
		}
		fpath = idx
	}
	if _, ok := cfg.Extensions[path.Ext(fpath)]; !ok {
		return md.Next.ServeHTTP(w, r)
	}
	f, err := md.FileSys.Open(fpath)
	switch {
	case err == nil:  
	case os.IsPermission(err):
		return http.StatusForbidden, err
	case os.IsNotExist(err):
		return http.StatusNotFound, nil
	default:  
		return http.StatusInternalServerError, err
	}
	defer f.Close()
	fs, err := f.Stat()
	if err != nil {
		return http.StatusGone, nil
	}
	lastModTime = latest(lastModTime, fs.ModTime())
	ctx := httpserver.NewContextWithHeader(w.Header())
	ctx.Root = md.FileSys
	ctx.Req = r
	ctx.URL = r.URL
	html, err := cfg.Markdown(title(fpath), f, dirents, ctx)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Content-Length", strconv.Itoa(len(html)))
	httpserver.SetLastModifiedHeader(w, lastModTime)
	if r.Method == http.MethodGet {
		if _, err := w.Write(html); err != nil {
			log.Println("[ERROR] failed to write html response: ", err)
		}
	}
	return http.StatusOK, nil
}
func latest(t ...time.Time) time.Time {
	var last time.Time
	for _, tt := range t {
		if tt.After(last) {
			last = tt
		}
	}
	return last
}