-
Notifications
You must be signed in to change notification settings - Fork 0
/
AttachmentResponse.go
91 lines (74 loc) · 2.28 KB
/
AttachmentResponse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package goboot
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gofiber/fiber/v2"
"github.com/lamgor666/goboot-common/util/mimex"
"io/ioutil"
)
type AttachmentResponse struct {
buf []byte
mimeType string
attachmentFileName string
}
func NewAttachmentResponseFromFile(fpath, attachmentFileName string, mimeType ...string) AttachmentResponse {
buf, _ := ioutil.ReadFile(fpath)
var _mimeType string
if len(mimeType) > 0 {
_mimeType = mimeType[0]
}
if _mimeType == "" {
_mimeType = mimex.GetMimeType(buf)
}
return AttachmentResponse{
buf: buf,
mimeType: _mimeType,
attachmentFileName: attachmentFileName,
}
}
func NewAttachmentResponseFromBuffer(buf []byte, attachmentFileName string, mimeType ...string) AttachmentResponse {
var _mimeType string
if len(mimeType) > 0 {
_mimeType = mimeType[0]
}
if _mimeType == "" {
_mimeType = mimex.GetMimeType(buf)
}
return AttachmentResponse{
buf: buf,
mimeType: _mimeType,
attachmentFileName: attachmentFileName,
}
}
func (p AttachmentResponse) GetContentType() string {
if p.mimeType == "" {
return fiber.MIMEOctetStream
}
return p.mimeType
}
func (p AttachmentResponse) GetContents() (int, string) {
if len(p.buf) < 1 || p.attachmentFileName == "" {
return 400, ""
}
return 200, ""
}
func (p AttachmentResponse) Buffer() []byte {
return p.buf
}
func (p AttachmentResponse) AddSpecifyHeaders(arg0 interface{}) {
disposition := fmt.Sprintf(`attachment; filename="%s"`, p.attachmentFileName)
if ctx, ok := arg0.(*fiber.Ctx); ok {
ctx.Set(fiber.HeaderContentType, p.GetContentType())
ctx.Set(fiber.HeaderContentLength, fmt.Sprintf("%d", len(p.buf)))
ctx.Set(fiber.HeaderTransferEncoding, "binary")
ctx.Set(fiber.HeaderContentDisposition, disposition)
ctx.Set(fiber.HeaderCacheControl, "no-cache, no-store, max-age=0, must-revalidate")
ctx.Set(fiber.HeaderPragma, "public")
} else if ctx, ok := arg0.(*gin.Context); ok {
ctx.Header(fiber.HeaderContentLength, fmt.Sprintf("%d", len(p.buf)))
ctx.Header(fiber.HeaderTransferEncoding, "binary")
ctx.Header(fiber.HeaderContentDisposition, disposition)
ctx.Header(fiber.HeaderCacheControl, "no-cache, no-store, max-age=0, must-revalidate")
ctx.Header(fiber.HeaderPragma, "public")
}
}