-
Notifications
You must be signed in to change notification settings - Fork 5
/
httpsrv.go
92 lines (76 loc) · 2.06 KB
/
httpsrv.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
83
84
85
86
87
88
89
90
91
92
package preview
import (
"context"
"fmt"
"io"
"net/http"
"path"
"strconv"
"github.com/nyaxt/otaru/apiserver"
"github.com/nyaxt/otaru/cli"
"github.com/nyaxt/otaru/logger"
"go.uber.org/zap"
)
const MaxArchiveSize = 512 * 1024 * 1024 // 512MiB
const MaxPreviewSize = 8 * 1024 * 1024 // 8MiB
const MaxTextPreviewSize = 32 * 1024 // 32KiB
var mylog = logger.Registry().Category("fe-preview")
type server struct {
cfg *cli.CliConfig
zp *zipPreviewer
}
func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
return
}
q := req.URL.Query()
opath := q.Get("opath")
idx, err := strconv.Atoi(q.Get("i"))
if err != nil {
idx = -1
}
ctx := req.Context()
ext := path.Ext(opath)
switch ext {
case ".zip":
if err := s.zp.Serve(ctx, opath, idx, w); err != nil {
zap.S().Warnf("zip preview failed: %v", err)
http.Error(w, "zip preview failed", http.StatusInternalServerError)
return
}
case ".txt", ".json", ".c", ".h", ".md":
if err := s.dumpAsText(ctx, opath, w); err != nil {
zap.S().Warnf("text preview failed: %v", err)
http.Error(w, "text preview failed", http.StatusInternalServerError)
return
}
default:
http.Error(w, fmt.Sprintf("no preview for %q", ext), http.StatusUnsupportedMediaType)
}
}
func (s *server) dumpAsText(ctx context.Context, opath string, w http.ResponseWriter) error {
r, err := cli.NewReader(opath, cli.WithCliConfig(s.cfg), cli.WithContext(ctx))
if err != nil {
return fmt.Errorf("Failed to start read of given opath %q. err: %v", opath, err)
}
defer r.Close()
if r.Size() > MaxTextPreviewSize {
return fmt.Errorf("File too large for text preview.")
}
w.Header().Set("Content-Type", "text/plain")
if _, err := io.Copy(w, r); err != nil {
return err
}
return nil
}
func Install(cfg *cli.CliConfig) apiserver.Option {
s := &server{
cfg: cfg,
zp: &zipPreviewer{cfg},
}
return apiserver.AddMuxHook(func(_ context.Context, mux *http.ServeMux) error {
mux.Handle("/preview", s)
return nil
})
}