/
files.go
82 lines (69 loc) · 1.89 KB
/
files.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package files
import (
"context"
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
const errorMessage = "<!DOCTYPE HTML><html><head><title>File uploader</title><style>body{font-size:2em;width: 60%;margin-left:auto;margin-right:auto;margin-top:80px;}</style></head><body>Error</body></html>"
var ErrNoZipSuffix = errors.New("path doesn't have '.zip' suffix")
func New(path string) http.Handler {
return &handler{
path: path,
}
}
type handler struct {
path string
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentOSPath := filepath.Join(
h.path,
filepath.Join(
strings.Split(
strings.TrimPrefix(r.URL.Path, RootURLPath),
"/",
)...,
),
)
log := hlog.FromRequest(r)
handler, err := getTargetHandler(ctx, r.URL.Query(), r.URL.Path, currentOSPath)
if err != nil {
log.Err(err).Msg("error while creating a target handler")
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
if err := handler.Handle(ctx, w); err != nil {
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
}
func getTargetHandler(ctx context.Context, queryValues url.Values, urlPath, osPath string) (targetHandler, error) {
log := zerolog.Ctx(ctx).With().Str("urlPath", urlPath).Str("osPath", osPath).Logger()
log.Debug().Msg("obtaining target for a request")
handleArchive := queryValues.Get("archive") == "true"
if handleArchive {
if !strings.HasSuffix(osPath, ".zip") {
log.Warn().Msg("path doesn't have '.zip' suffix")
return nil, ErrNoZipSuffix
}
osPath = osPath[0 : len(osPath)-4]
}
fileInfo, err := os.Stat(osPath)
if err != nil {
return nil, err
}
if fileInfo.IsDir() {
if handleArchive {
return newZipHandler(osPath), nil
} else {
return newDirHandler(osPath, urlPath), nil
}
}
return newSingleFile(osPath), nil
}