forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read.go
88 lines (72 loc) · 1.62 KB
/
read.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
package pipes
import (
"io"
"net/http"
"code.cloudfoundry.org/lager"
"github.com/concourse/atc"
)
func (s *Server) ReadPipe(w http.ResponseWriter, r *http.Request) {
logger := s.logger.Session("read-pipe")
pipeID := r.FormValue(":pipe_id")
dbPipe, err := s.db.GetPipe(pipeID)
if err != nil {
logger.Error("failed-to-get-pipe", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
closed := w.(http.CloseNotifier).CloseNotify()
if dbPipe.URL == s.url {
s.pipesL.RLock()
pipe, found := s.pipes[pipeID]
s.pipesL.RUnlock()
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
copied := make(chan struct{})
go func() {
io.Copy(w, pipe.read)
close(copied)
}()
dance:
for {
select {
case <-copied:
break dance
case <-closed:
// connection died; terminate the pipe
pipe.write.Close()
}
}
s.pipesL.Lock()
delete(s.pipes, pipeID)
s.pipesL.Unlock()
} else {
logger.Debug("forwarding-pipe-read-request", lager.Data{"pipe-url": dbPipe.URL})
response, err := s.forwardRequest(w, r, dbPipe.URL, atc.ReadPipe, dbPipe.ID)
if err != nil {
logger.Error("failed-to-forward-request", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(response.StatusCode)
w.(http.Flusher).Flush()
copied := make(chan struct{})
go func() {
io.Copy(w, response.Body)
close(copied)
}()
danceMore:
for {
select {
case <-copied:
break danceMore
case <-closed:
// connection died; terminate the pipe
w.WriteHeader(http.StatusGatewayTimeout)
}
}
}
}