mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-10 14:44:37 +08:00
Merge e521dba4400cefab9549d4152b5dc64711c20a29 into d9e5cdf9c6f9c1643be6e081516469c71645d93d
This commit is contained in:
commit
78e4fe63d8
@ -1222,6 +1222,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 2026 Gin Core Team. 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) {
|
||||
|
||||
@ -375,6 +375,22 @@ func TestRenderXML(t *testing.T) {
|
||||
assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
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