-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremote_get.go
102 lines (86 loc) · 2.2 KB
/
remote_get.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
93
94
95
96
97
98
99
100
101
102
package gemdrive
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
func (s *Server) remoteGet(w http.ResponseWriter, r *http.Request) {
key, _ := extractToken(r)
if key == "" {
key = "public"
}
bodyJson, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(400)
io.WriteString(w, err.Error())
return
}
reqData := &RemoteGetRequest{}
err = json.Unmarshal(bodyJson, reqData)
if err != nil {
w.WriteHeader(400)
io.WriteString(w, err.Error())
return
}
if reqData.Source == "" {
w.WriteHeader(400)
io.WriteString(w, "remote-get: Missing source "+reqData.Source)
return
}
if reqData.Destination == "" {
w.WriteHeader(400)
io.WriteString(w, "remote-get: Missing destination "+reqData.Destination)
return
}
if !s.keyAuth.CanWrite(key, reqData.Destination) {
w.WriteHeader(403)
io.WriteString(w, "remote-get: You don't have permission to write to "+reqData.Destination)
return
}
backend, ok := s.backend.(WritableBackend)
if !ok {
w.WriteHeader(500)
io.WriteString(w, "remote-get: Backend does not support writing")
return
}
resp, err := http.Get(reqData.Source)
if err != nil {
w.WriteHeader(500)
io.WriteString(w, "remote-get: "+err.Error())
return
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
w.WriteHeader(500)
io.WriteString(w, fmt.Sprintf("remote-get: Failed with status %d", resp.StatusCode))
return
}
err = backend.Write(reqData.Destination, resp.Body, reqData.DestinationOffset, resp.ContentLength, reqData.Overwrite, reqData.Truncate)
if err != nil {
w.WriteHeader(500)
io.WriteString(w, err.Error())
return
}
if reqData.PreserveAttributes {
lastModified := resp.Header.Get("Last-Modified")
isExecutableHeader := resp.Header.Get("GemDrive-IsExecutable")
if lastModified != "" || isExecutableHeader != "" {
modTime, err := time.Parse(http.TimeFormat, lastModified)
if err != nil {
w.WriteHeader(500)
io.WriteString(w, err.Error())
return
}
isExecutable := isExecutableHeader == "true"
err = backend.SetAttributes(reqData.Destination, modTime, isExecutable)
if err != nil {
w.WriteHeader(500)
io.WriteString(w, err.Error())
return
}
}
}
}