summaryrefslogtreecommitdiff
path: root/modules/caddyhttp/markdown/markdown.go
blob: 90d615a0a3a68b9348428b8b4490feffd1effd34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package markdown

import (
	"net/http"
	"strconv"

	"gopkg.in/russross/blackfriday.v2"

	"github.com/caddyserver/caddy"
	"github.com/caddyserver/caddy/modules/caddyhttp"
)

func init() {
	caddy.RegisterModule(caddy.Module{
		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 {
	mrw := &markdownResponseWriter{
		ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{ResponseWriter: w},
	}
	return next.ServeHTTP(mrw, r)
}

type markdownResponseWriter struct {
	*caddyhttp.ResponseWriterWrapper
	statusCode  int
	wroteHeader bool
}

func (mrw *markdownResponseWriter) WriteHeader(code int) {
	mrw.statusCode = code
}

func (mrw *markdownResponseWriter) Write(d []byte) (int, error) {
	output := blackfriday.Run(d)
	if !mrw.wroteHeader {
		mrw.Header().Set("Content-Length", strconv.Itoa(len(output)))
		mrw.Header().Set("Content-Type", "text/html; charset=utf-8")
		mrw.WriteHeader(mrw.statusCode)
		mrw.wroteHeader = true
	}
	return mrw.ResponseWriter.Write(output)
}

// Interface guard
var _ caddyhttp.MiddlewareHandler = (*Markdown)(nil)