/
server.go
100 lines (88 loc) · 1.72 KB
/
server.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
package rgo
import (
"io"
"net"
"net/http"
"strings"
"sync"
"github.com/facebookgo/httpdown"
)
type readerDone struct {
r io.Reader
done chan<- struct{}
}
type server struct {
s httpdown.Server
port int
mu sync.Mutex
data map[string][]byte
fmu sync.Mutex
fwd map[string]chan<- readerDone
}
func (s *server) putData(key string, val []byte) {
defer s.mu.Unlock()
s.mu.Lock()
s.data[key] = val
}
func (s *server) rmData(key string) {
defer s.mu.Unlock()
s.mu.Lock()
delete(s.data, key)
}
func (s *server) putFwd(key string, c chan<- readerDone) {
defer s.fmu.Unlock()
s.fmu.Lock()
s.fwd[key] = c
}
func (s *server) rmFwd(key string) {
defer s.fmu.Unlock()
s.fmu.Lock()
delete(s.fwd, key)
}
func (s *server) httpHandler(w http.ResponseWriter, r *http.Request) {
path := strings.TrimLeft(r.URL.Path, "/")
if r.Method == "GET" {
s.mu.Lock()
data, ok := s.data[path]
s.mu.Unlock()
if !ok {
http.Error(w, "Not found", http.StatusNotFound)
return
}
w.Write(data)
return
} else if r.Method == "PUT" {
s.fmu.Lock()
c, ok := s.fwd[path]
s.fmu.Unlock()
if !ok {
r.Body.Close()
http.Error(w, "", http.StatusInternalServerError)
return
}
done := make(chan struct{})
rd := readerDone{r.Body, done}
c <- rd
<-done
r.Body.Close()
return
}
http.Error(w, "", http.StatusMethodNotAllowed)
}
func newServer() (*server, error) {
var s server
s.data = make(map[string][]byte)
s.fwd = make(map[string]chan<- readerDone)
hs := http.Server{
Addr: ":0",
Handler: http.HandlerFunc(s.httpHandler),
}
ln, err := net.Listen("tcp", ":0")
if err != nil {
return nil, err
}
var h httpdown.HTTP
s.s = h.Serve(&hs, ln)
s.port = ln.Addr().(*net.TCPAddr).Port
return &s, nil
}