diff options
author | Matthew Holt <mholt@users.noreply.github.com> | 2019-05-23 14:41:43 -0600 |
---|---|---|
committer | Matthew Holt <mholt@users.noreply.github.com> | 2019-05-23 14:41:43 -0600 |
commit | 34a25dd5580948ff5b83843b81e72bda1b133189 (patch) | |
tree | e46c60848db71650d0ac3dbbe632667c8fa41f6a | |
parent | 9e576c76e74ff3d5b8d5a384fecf2a2ca191b402 (diff) |
Add very simple markdown middleware for now
-rw-r--r-- | cmd/caddy2/main.go | 2 | ||||
-rw-r--r-- | modules/caddyhttp/markdown/markdown.go | 53 |
2 files changed, 55 insertions, 0 deletions
diff --git a/cmd/caddy2/main.go b/cmd/caddy2/main.go index 59239a2..daed20e 100644 --- a/cmd/caddy2/main.go +++ b/cmd/caddy2/main.go @@ -8,6 +8,8 @@ import ( _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/caddylog" _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/fileserver" _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/headers" + _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/markdown" + _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/requestbody" _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/reverseproxy" _ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/rewrite" _ "bitbucket.org/lightcodelabs/caddy2/modules/caddytls" diff --git a/modules/caddyhttp/markdown/markdown.go b/modules/caddyhttp/markdown/markdown.go new file mode 100644 index 0000000..9c23e44 --- /dev/null +++ b/modules/caddyhttp/markdown/markdown.go @@ -0,0 +1,53 @@ +package markdown + +import ( + "net/http" + "strconv" + + "gopkg.in/russross/blackfriday.v2" + + "bitbucket.org/lightcodelabs/caddy2" + "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp" +) + +func init() { + caddy2.RegisterModule(caddy2.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) |