Refactor common code to download invoice and expenses attachments
This commit is contained in:
parent
4deb698265
commit
58cef8c00b
|
@ -0,0 +1,25 @@
|
|||
package pkg
|
||||
|
||||
import (
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func serveAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params, sql string) {
|
||||
slug := params[0].Value
|
||||
if !ValidUuid(slug) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
conn := getConn(r)
|
||||
var contentType string
|
||||
var content []byte
|
||||
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), sql, slug).Scan(&contentType, &content)) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10))
|
||||
_, _ = w.Write(content)
|
||||
}
|
|
@ -635,28 +635,13 @@ func HandleUpdateExpenseTags(w http.ResponseWriter, r *http.Request, params http
|
|||
}
|
||||
|
||||
func ServeExpenseAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
slug := params[0].Value
|
||||
if !ValidUuid(slug) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
conn := getConn(r)
|
||||
var contentType string
|
||||
var content []byte
|
||||
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `
|
||||
serveAttachment(w, r, params, `
|
||||
select mime_type
|
||||
, content
|
||||
from expense
|
||||
join expense_attachment using (expense_id)
|
||||
where slug = $1
|
||||
`, slug).Scan(&contentType, &content)) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(content)
|
||||
`)
|
||||
}
|
||||
|
||||
func HandleEditExpenseAction(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
|
|
|
@ -1514,26 +1514,11 @@ func HandleUpdateInvoiceTags(w http.ResponseWriter, r *http.Request, params http
|
|||
}
|
||||
|
||||
func ServeInvoiceAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
|
||||
slug := params[0].Value
|
||||
if !ValidUuid(slug) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
conn := getConn(r)
|
||||
var contentType string
|
||||
var content []byte
|
||||
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `
|
||||
serveAttachment(w, r, params, `
|
||||
select mime_type
|
||||
, content
|
||||
from invoice
|
||||
join invoice_attachment using (invoice_id)
|
||||
where slug = $1
|
||||
`, slug).Scan(&contentType, &content)) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(content)
|
||||
`)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue