-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
86 lines (70 loc) · 2.25 KB
/
http.go
File metadata and controls
86 lines (70 loc) · 2.25 KB
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
package main
import (
"bytes"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
)
const DownThemAllArchiveFilename = "DownThemAll"
type HttpHandlers struct {
QuickURL *QuickURL
}
var MIME = map[string]string{
"tar.gz": "application/gzip",
"zip": "application/zip",
}
func (quh *HttpHandlers) CreateArchive(w http.ResponseWriter, r *http.Request) {
filename := mux.Vars(r)["filename"]
format := mux.Vars(r)["archive"]
contentType, ok := MIME[format]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
archiveFilename := fmt.Sprintf("%v.%v", filename, format) // TODO is it too simple?
log.Debugf("request %v", archiveFilename)
if path, ok := quh.QuickURL.ServingEntries[filename]; ok {
result, err := quh.QuickURL.CreateArchive([]string{path}, format)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Fatal(err)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, archiveFilename))
http.ServeContent(w, r, archiveFilename, time.Now(), bytes.NewReader(result))
} else {
w.WriteHeader(http.StatusNotFound)
}
}
func (quh *HttpHandlers) OriginalFile(w http.ResponseWriter, r *http.Request) {
filename := mux.Vars(r)["filename"]
log.Debug(filename)
if path, exists := quh.QuickURL.ServingEntries[filename]; exists {
http.ServeFile(w, r, path)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
func (quh *HttpHandlers) DownThemAll(w http.ResponseWriter, r *http.Request) {
format := mux.Vars(r)["archive"]
contentType, ok := MIME[format]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
archiveFilename := fmt.Sprintf("%v_%v.%v", DownThemAllArchiveFilename, time.Now().Unix(), format) // TODO is it too simple?
log.Debugf("request %v", archiveFilename)
result, err := quh.QuickURL.CreateArchive(maps.Values(quh.QuickURL.ServingEntries), format)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Fatal(err)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, archiveFilename))
http.ServeContent(w, r, archiveFilename, time.Now(), bytes.NewReader(result))
}