v0.0.469
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 3m26s
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 3m26s
This commit is contained in:
73
ginext/responseFile.go
Normal file
73
ginext/responseFile.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package ginext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
"os"
|
||||
)
|
||||
|
||||
type fileHTTPResponse struct {
|
||||
mimetype string
|
||||
filepath string
|
||||
filename *string
|
||||
headers []headerval
|
||||
cookies []cookieval
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) Write(g *gin.Context) {
|
||||
g.Header("Content-Type", j.mimetype) // if we don't set it here gin does weird file-sniffing later...
|
||||
if j.filename != nil {
|
||||
g.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", *j.filename))
|
||||
|
||||
}
|
||||
for _, v := range j.headers {
|
||||
g.Header(v.Key, v.Val)
|
||||
}
|
||||
for _, v := range j.cookies {
|
||||
g.SetCookie(v.name, v.value, v.maxAge, v.path, v.domain, v.secure, v.httpOnly)
|
||||
}
|
||||
g.File(j.filepath)
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) WithHeader(k string, v string) HTTPResponse {
|
||||
j.headers = append(j.headers, headerval{k, v})
|
||||
return j
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) WithCookie(name string, value string, maxAge int, path string, domain string, secure bool, httpOnly bool) HTTPResponse {
|
||||
j.cookies = append(j.cookies, cookieval{name, value, maxAge, path, domain, secure, httpOnly})
|
||||
return j
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) IsSuccess() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) Statuscode() int {
|
||||
return 200
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) BodyString(*gin.Context) *string {
|
||||
data, err := os.ReadFile(j.filepath)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return langext.Ptr(string(data))
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) ContentType() string {
|
||||
return j.mimetype
|
||||
}
|
||||
|
||||
func (j fileHTTPResponse) Headers() []string {
|
||||
return langext.ArrMap(j.headers, func(v headerval) string { return v.Key + "=" + v.Val })
|
||||
}
|
||||
|
||||
func File(mimetype string, filepath string) HTTPResponse {
|
||||
return &fileHTTPResponse{mimetype: mimetype, filepath: filepath}
|
||||
}
|
||||
|
||||
func Download(mimetype string, filepath string, filename string) HTTPResponse {
|
||||
return &fileHTTPResponse{mimetype: mimetype, filepath: filepath, filename: &filename}
|
||||
}
|
Reference in New Issue
Block a user