forked from everytv/test2doc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
108 lines (87 loc) · 2.13 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
101
102
103
104
105
106
107
108
package test
import (
"log"
"net/http"
"net/http/httptest"
"sort"
"github.com/everytv/test2doc/doc"
"github.com/everytv/test2doc/doc/parse"
)
// resources = map[uri]Resource
var resources = map[string]*doc.Resource{}
type Server struct {
*httptest.Server
doc *doc.Doc
}
// TODO: filter out 404 responses
func NewServer(handler http.Handler) (s *Server, err error) {
// check if url var extractor func is set
if parse.Extractor == nil {
panic("please set a URLVarExtractor.")
}
outDoc, err := doc.NewDoc(".")
if err != nil {
return s, err
}
httptestServer := httptest.NewServer(handleAndRecord(handler, outDoc))
return &Server{
httptestServer,
outDoc,
}, nil
}
func (s *Server) Finish() {
s.Close()
// sort resources by path
var uris []string
for k := range resources {
uris = append(uris, k)
}
sort.Strings(uris)
for _, uri := range uris {
s.doc.AddResource(resources[uri])
}
err := s.doc.Write()
if err != nil {
panic(err.Error())
}
}
func handleAndRecord(handler http.Handler, outDoc *doc.Doc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
// copy request body into Request object
docReq, err := doc.NewRequest(req)
if err != nil {
log.Println("Error:", err.Error())
return
}
// record response
rw := httptest.NewRecorder()
resp := NewResponseWriter(rw)
handler.ServeHTTP(resp, req)
// setup resource
u := doc.NewURL(req)
path := u.ParameterizedPath
if resources[path] == nil {
resources[path] = doc.NewResource(u)
}
// store response body in Response object
docResp := doc.NewResponse(resp.W)
// find action
action := resources[path].FindAction(req.Method)
if action == nil {
// make new action
action, err = doc.NewAction(req.Method, resp.HandlerInfo.FuncName)
if err != nil {
log.Println("Error:", err.Error())
return
}
// add Action to Resource's list of Actions
resources[path].AddAction(action)
}
// add request, response to action
action.AddRequest(docReq, docResp)
// copy response over to w
doc.CopyHeader(w.Header(), resp.Header())
w.WriteHeader(resp.W.Code)
w.Write(resp.W.Body.Bytes())
}
}