mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-04 09:48:17 +08:00
render: add PDF renderer and tests
This commit is contained in:
parent
472d086af2
commit
33e8afb7f6
@ -1224,6 +1224,12 @@ func (c *Context) XML(code int, obj any) {
|
||||
c.Render(code, render.XML{Data: obj})
|
||||
}
|
||||
|
||||
// PDF writes the given PDF binary data into the response body.
|
||||
// It also sets the Content-Type as "application/pdf".
|
||||
func (c *Context) PDF(code int, data []byte) {
|
||||
c.Render(code, render.PDF{Data: data})
|
||||
}
|
||||
|
||||
// YAML serializes the given struct as YAML into the response body.
|
||||
func (c *Context) YAML(code int, obj any) {
|
||||
c.Render(code, render.YAML{Data: obj})
|
||||
|
||||
26
render/pdf.go
Normal file
26
render/pdf.go
Normal file
@ -0,0 +1,26 @@
|
||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package render
|
||||
|
||||
import "net/http"
|
||||
|
||||
// PDF contains the given PDF binary data.
|
||||
type PDF struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
var pdfContentType = []string{"application/pdf"}
|
||||
|
||||
// Render (PDF) writes PDF data with custom ContentType.
|
||||
func (r PDF) Render(w http.ResponseWriter) error {
|
||||
r.WriteContentType(w)
|
||||
_, err := w.Write(r.Data)
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteContentType (PDF) writes PDF ContentType for response.
|
||||
func (r PDF) WriteContentType(w http.ResponseWriter) {
|
||||
writeContentType(w, pdfContentType)
|
||||
}
|
||||
@ -31,6 +31,7 @@ var (
|
||||
_ Render = (*AsciiJSON)(nil)
|
||||
_ Render = (*ProtoBuf)(nil)
|
||||
_ Render = (*TOML)(nil)
|
||||
_ Render = (*PDF)(nil)
|
||||
)
|
||||
|
||||
func writeContentType(w http.ResponseWriter, value []string) {
|
||||
|
||||
@ -466,6 +466,22 @@ func TestRenderXMLError(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "xml: unsupported type: chan int")
|
||||
}
|
||||
|
||||
func TestRenderPDF(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
data := []byte("%Test pdf content")
|
||||
|
||||
pdf := PDF{data}
|
||||
|
||||
pdf.WriteContentType(w)
|
||||
assert.Equal(t, "application/pdf", w.Header().Get("Content-Type"))
|
||||
|
||||
err := pdf.Render(w)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, data, w.Body.Bytes())
|
||||
assert.Equal(t, "application/pdf", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestRenderRedirect(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "/test-redirect", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user