diff --git a/postrender.go b/postrender.go index 83fb5ad..02b156b 100644 --- a/postrender.go +++ b/postrender.go @@ -11,9 +11,11 @@ package writefreely import ( + "encoding/json" "fmt" "html" "html/template" + "net/http" "regexp" "strings" "unicode" @@ -21,7 +23,9 @@ import ( "github.com/microcosm-cc/bluemonday" stripmd "github.com/writeas/go-strip-markdown" + "github.com/writeas/impart" blackfriday "github.com/writeas/saturday" + "github.com/writeas/web-core/log" "github.com/writeas/web-core/stringmanip" "github.com/writeas/writefreely/config" "github.com/writeas/writefreely/parse" @@ -234,3 +238,31 @@ func shortPostDescription(content string) string { } return strings.TrimSpace(fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1))) } + +func handleRenderMarkdown(app *App, w http.ResponseWriter, r *http.Request) error { + if !IsJSON(r) { + return impart.HTTPError{Status: http.StatusUnsupportedMediaType, Message: "Markdown API only supports JSON requests"} + } + + in := struct { + BaseURL string `json:"base_url"` + RawBody string `json:"raw_body"` + }{ + BaseURL: "", + } + + decoder := json.NewDecoder(r.Body) + err := decoder.Decode(&in) + if err != nil { + log.Error("Couldn't parse markdown JSON request: %v", err) + return ErrBadJSON + } + + out := struct { + Body string `json:"body"` + }{ + Body: applyMarkdown([]byte(in.RawBody), in.BaseURL, app.cfg), + } + + return impart.WriteSuccess(w, out, http.StatusOK) +} diff --git a/routes.go b/routes.go index a3d4a1c..18f8477 100644 --- a/routes.go +++ b/routes.go @@ -113,6 +113,8 @@ func InitRoutes(apper Apper, r *mux.Router) *mux.Router { // Sign up validation write.HandleFunc("/api/alias", handler.All(handleUsernameCheck)).Methods("POST") + write.HandleFunc("/api/markdown", handler.All(handleRenderMarkdown)).Methods("POST") + // Handle collections write.HandleFunc("/api/collections", handler.All(newCollection)).Methods("POST") apiColls := write.PathPrefix("/api/collections/").Subrouter()