From d2480cb3aa78e6faa4891913b6543c1e8b70340a Mon Sep 17 00:00:00 2001 From: Rob Loranger Date: Tue, 15 Oct 2019 15:03:45 -0700 Subject: [PATCH] add basic API endpoint for rendering markdown --- postrender.go | 42 ++++++++++++++++++++++++++++++++++++++++++ routes.go | 3 +++ 2 files changed, 45 insertions(+) diff --git a/postrender.go b/postrender.go index 83fb5ad..2f55896 100644 --- a/postrender.go +++ b/postrender.go @@ -11,9 +11,12 @@ package writefreely import ( + "encoding/json" "fmt" "html" "html/template" + "io/ioutil" + "net/http" "regexp" "strings" "unicode" @@ -234,3 +237,42 @@ 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 { + // TODO: accept header + if !IsJSON(r.Header.Get("Content-Type")) { + fmt.Println("missing header") + } + + in := struct { + BaseURL string `json:"base_url"` + RawBody string `json:"raw_body"` + }{ + BaseURL: "", + } + + body, err := ioutil.ReadAll(r.Body) + if err != nil { + return ErrInternalGeneral + } + + err = json.Unmarshal(body, &in) + if err != nil { + return ErrInternalGeneral + } + + out := struct { + Body string `json:"body"` + }{ + Body: applyMarkdown([]byte(in.RawBody), in.BaseURL, nil), + } + + js, err := json.Marshal(out) + if err != nil { + return ErrInternalGeneral + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(js) + return nil +} diff --git a/routes.go b/routes.go index 0113e93..25a8bf3 100644 --- a/routes.go +++ b/routes.go @@ -110,6 +110,9 @@ func InitRoutes(apper Apper, r *mux.Router) *mux.Router { // Sign up validation write.HandleFunc("/api/alias", handler.All(handleUsernameCheck)).Methods("POST") + apiGenerate := write.PathPrefix("/api/generate/").Subrouter() + apiGenerate.HandleFunc("/markdownify", handler.All(handleRenderMarkdown)).Methods("POST") + // Handle collections write.HandleFunc("/api/collections", handler.All(newCollection)).Methods("POST") apiColls := write.PathPrefix("/api/collections/").Subrouter()