2019-05-23 15:41:43 -05:00
|
|
|
package markdown
|
|
|
|
|
|
|
|
import (
|
2019-06-20 22:49:45 -05:00
|
|
|
"bytes"
|
2019-05-23 15:41:43 -05:00
|
|
|
"net/http"
|
|
|
|
"strconv"
|
2019-06-20 22:49:45 -05:00
|
|
|
"sync"
|
2019-05-23 15:41:43 -05:00
|
|
|
|
|
|
|
"gopkg.in/russross/blackfriday.v2"
|
|
|
|
|
2019-06-14 12:58:28 -05:00
|
|
|
"github.com/caddyserver/caddy"
|
|
|
|
"github.com/caddyserver/caddy/modules/caddyhttp"
|
2019-05-23 15:41:43 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2019-06-14 12:58:28 -05:00
|
|
|
caddy.RegisterModule(caddy.Module{
|
2019-05-23 15:41:43 -05:00
|
|
|
Name: "http.middleware.markdown",
|
|
|
|
New: func() interface{} { return new(Markdown) },
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Markdown is a middleware for rendering a Markdown response body.
|
|
|
|
type Markdown struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Markdown) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
|
2019-06-20 22:49:45 -05:00
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
|
|
|
rr := caddyhttp.NewResponseRecorder(w, buf)
|
|
|
|
|
|
|
|
err := next.ServeHTTP(rr, r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-05-23 15:41:43 -05:00
|
|
|
}
|
|
|
|
|
2019-06-20 22:49:45 -05:00
|
|
|
output := blackfriday.Run(buf.Bytes())
|
2019-05-23 15:41:43 -05:00
|
|
|
|
2019-06-20 22:49:45 -05:00
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(output)))
|
|
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
|
|
w.Header().Del("Accept-Ranges") // we don't know ranges for dynamically-created content
|
|
|
|
w.Header().Del("Etag") // don't know a way to quickly generate etag for dynamic content
|
|
|
|
w.Header().Del("Last-Modified") // useless for dynamic content since it's always changing
|
|
|
|
|
|
|
|
w.WriteHeader(rr.Status())
|
|
|
|
w.Write(output)
|
|
|
|
|
|
|
|
return nil
|
2019-05-23 15:41:43 -05:00
|
|
|
}
|
|
|
|
|
2019-06-20 22:49:45 -05:00
|
|
|
var bufPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
2019-05-23 15:41:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Interface guard
|
|
|
|
var _ caddyhttp.MiddlewareHandler = (*Markdown)(nil)
|