diff --git a/Makefile b/Makefile index c5f99af..d58ec50 100644 --- a/Makefile +++ b/Makefile @@ -26,6 +26,7 @@ RELEASE_IMAGE:=$(REPO):$(VERSION) RELEASE_IMAGE_ALIASE:=$(REPO):latest .DEFAULT_GOAL:=help +.PHONY: image-wkhtml image-develop image-release help: # Output usage documentation @echo "Usage: make " diff --git a/api/handlers.go b/api/handlers.go index c64ba48..1b51a9f 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -3,6 +3,7 @@ package api import ( "encoding/json" "net/http" + "io/ioutil" "github.com/opsway/documents/cmd/document" "github.com/opsway/documents/cmd/template" @@ -31,6 +32,35 @@ func HTMLToPDFGet(w http.ResponseWriter, r *http.Request) { } } +// BodyToPDFPost renders pdf from request's HTTP body +func BodyToPDFPost(w http.ResponseWriter, r *http.Request) { + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Failed to read a request body", http.StatusBadRequest) + return + } + + if body == nil { + http.Error(w, "Request body is empty", http.StatusBadRequest) + return + } + + content := string(body) + + pdf, err := document.NewPDF() + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + err = pdf.RenderByContent(w, content) + + if err != nil { + panic(err) + } +} + // RenderTemplateRequest refers request of rendering pdf type RenderTemplateRequest struct { TemplateName string `json:"templateName"` diff --git a/api/routers.go b/api/routers.go index 4616c51..0b1d262 100644 --- a/api/routers.go +++ b/api/routers.go @@ -88,6 +88,29 @@ var routes = Routes{ HTMLToPDFGet, }, + // swagger:operation POST /body-to-pdf BodyToPDFPost + // + // render request body to PDF + // + // --- + // produces: + // - application/pdf + // requestBody: + // text/html: + // schema: + // type: string + // responses: + // '200': + // description: A PDF file + // '422': + // description: Validation error + Route{ + "BodyToPDFPost", + strings.ToUpper("Post"), + "/body-to-pdf", + BodyToPDFPost, + }, + // swagger:operation POST /render-template RenderTemplatePost // // render template to PDF diff --git a/api/server_test.go b/api/server_test.go index 6e85522..ef0d0a5 100644 --- a/api/server_test.go +++ b/api/server_test.go @@ -37,6 +37,15 @@ func TestApi(t *testing.T) { So(resp.StatusCode, ShouldEqual, http.StatusOK) So(resp.Header.Get("Content-Type"), ShouldEqual, "application/pdf") }) + + Convey("Got PDF by request body", func() { + data := []byte(`

test

`) + bodyReader := bytes.NewReader(data) + resp, err := http.Post(srv.URL+"/body-to-pdf", "text/html", bodyReader) + So(err, ShouldBeNil) + So(resp.StatusCode, ShouldEqual, http.StatusOK) + So(resp.Header.Get("Content-Type"), ShouldEqual, "application/pdf") + }) }) Convey("PDF from template", t, func() {