package ginext import ( "fmt" "github.com/gin-gonic/gin" "gogs.mikescher.com/BlackForestBytes/goext/langext" ) type downloadDataHTTPResponse struct { statusCode int mimetype string data []byte filename *string headers []headerval cookies []cookieval } func (j downloadDataHTTPResponse) 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.Data(j.statusCode, j.mimetype, j.data) } func (j downloadDataHTTPResponse) WithHeader(k string, v string) HTTPResponse { j.headers = append(j.headers, headerval{k, v}) return j } func (j downloadDataHTTPResponse) 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 downloadDataHTTPResponse) IsSuccess() bool { return j.statusCode >= 200 && j.statusCode <= 399 } func (j downloadDataHTTPResponse) Statuscode() int { return j.statusCode } func (j downloadDataHTTPResponse) BodyString(*gin.Context) *string { return langext.Ptr(string(j.data)) } func (j downloadDataHTTPResponse) ContentType() string { return j.mimetype } func (j downloadDataHTTPResponse) Headers() []string { return langext.ArrMap(j.headers, func(v headerval) string { return v.Key + "=" + v.Val }) } func DownloadData(status int, mimetype string, filename string, data []byte) HTTPResponse { return &downloadDataHTTPResponse{statusCode: status, mimetype: mimetype, data: data, filename: &filename} }