Merge pull request #197 from writeas/markdown-API

add basic API endpoint for rendering markdown

Ref T519
This commit is contained in:
Matt Baer 2020-01-03 13:47:50 -05:00 committed by GitHub
commit a4579719cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 0 deletions

View File

@ -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)
}

View File

@ -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()