-
Notifications
You must be signed in to change notification settings - Fork 4
/
get_asset.go
65 lines (48 loc) · 1.42 KB
/
get_asset.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
package handlers
import (
"database/sql"
"log"
"net/http"
db "github.com/Tech-With-Tim/cdn/db/sqlc"
"github.com/Tech-With-Tim/cdn/utils"
"github.com/go-chi/chi/v5"
)
/*
Response: FileType | JSON
URL Parameters: AssetURL (string)
Description: "Return an asset, given the asset url. If the asset
is not found, a 404 error is returned. If it is found, the
asset is returned as per it's file type."
*/
func (s *Service) GetAsset() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var resp map[string]interface{}
var fileRow db.GetFileRow
var err error
url := chi.URLParam(r, "AssetUrl")
fileRow, err = s.getFile(url, r.Context())
if err != nil {
if err == sql.ErrNoRows {
resp = map[string]interface{}{"error": "Not Found",
"message": "No asset found with that url_path."}
utils.JSON(w, http.StatusNotFound, resp)
return
}
resp = map[string]interface{}{"error": "Something Unexpected Occurred."}
utils.JSON(w, http.StatusInternalServerError, resp)
log.Println(err.Error())
return
}
// FileRow:
// Data []byte `json:"data"`
// Mimetype string `json:"mimetype"`
w.Header().Set("Content-Type", fileRow.Mimetype)
_, err = w.Write(fileRow.Data)
if err != nil {
resp = map[string]interface{}{"error": "Something Unexpected Occurred."}
utils.JSON(w, http.StatusInternalServerError, resp)
log.Println(err.Error())
return
}
}
}